我想在 uitableview 中填充数据。我有不同类别的不同部分,每个类别包含不同数量的行。
- (NSInteger)numberOfSectionsInTableViewUITableView *)tableView
{
return allCategory.count;
}
- (NSString *)tableViewUITableView *)tableView titleForHeaderInSectionNSInteger)section {
NSString *heading = [allCategory objectAtIndex:section];
return heading;
}
-(NSInteger)tableViewUITableView *)tableView numberOfRowsInSectionNSInteger)section{
int count = 0;
NSString *heading = [allCategory objectAtIndex:section];
for (Product * cat in productArry) {
if ([cat.category containsString:heading]) {
count ++;
}
}
return count;
}
这是我根据类别返回多行的代码。
例如,我有一个类别名称“Engine”,它返回一个行数和一个类别名称“Blocks”,它返回 2 个行数。现在我想针对“cellForRowAtIndexPath”方法中的每个类别填充数据。如何针对每个类别填充正确的数据?
Best Answer-推荐答案 strong>
选项 1:
- (Product *)dataForRowAtIndexPathNSIndexPath *)indexPath {
int count = 0;
NSString *heading = [self.allCategory objectAtIndex:indexPath.section];
for (Product * product in self.productArry) {
if ([product.category containsString:heading]) {
if (count == indexPath.row) {
return product;
}
count++;
}
}
return nil;
}
- (UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPathNSIndexPath *)indexPath {
Product *product = [self dataForRowAtIndexPath:indexPath];
return nil;
}
选项 2:
或者您可能想要制作一个过滤数组
.h
@property (nonatomic, strong) NSArray *allCategory;
@property (nonatomic, strong) NSArray *productArry;
@property (nonatomic, strong) NSArray *products;
.m
- (NSArray *)products {
if (!_products) {
NSMutableArray *arrayCategoryProductArray = [[NSMutableArray alloc]init];
for(int i =0 ;i< self.allCategory.count;i++){
NSString *strCat = [self.allCategory objectAtIndex:i];
NSArray *filteredarray = [self.productArry filteredArrayUsingPredicate:[NSPredicate predicateWithFormat"(category == %@)", strCat]];
[arrayCategoryProductArray addObject : filteredarray];
}
_products = arrayCategoryProductArray;
}
return _products;
}
输入
<__NSArrayI 0x7866c8b0>(
<roduct: 0x78668460; category = A; name = A1>,
<roduct: 0x78663280; category = B; name = B1>,
<roduct: 0x7866c750; category = A; name = A2>,
<roduct: 0x7864c950; category = B; name = B2>,
<roduct: 0x786610a0; category = B; name = B3>
)
输出
<__NSArrayM 0x798449b0>(
<__NSArrayI 0x79839050>(
<roduct: 0x78668460; category = A; name = A1>,
<roduct: 0x7866c750; category = A; name = A2>
)
,
<__NSArrayI 0x798c7310>(
<roduct: 0x78663280; category = B; name = B1>,
<roduct: 0x7864c950; category = B; name = B2>,
<roduct: 0x786610a0; category = B; name = B3>
)
)
所以
- (Product *)dataForRowAtIndexPathNSIndexPath *)indexPath {
Product *product = [[self.products objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
return product;
}
- (UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
Product *product = [self dataForRowAtIndexPath:indexPath];
return nil;
}
关于ios - 使用部分类别填充表格 View ,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/36329645/
|