【发布时间】:2014-09-14 09:46:04
【问题描述】:
我正在尝试将章节标题添加到我的 UITableView。我能够创建部分并正确计算每个部分中的元素数量,但是当我调用我的 cellForRowAtIndexPath 方法时,表格会重复两个部分中的数据。
这是我准备 UITableView 部分内容的地方:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
int sections = 0;
if (sectionOneCount>0) {
sections++;
}
if (sectionTwoCount>0) {
sections++;
}
return sections;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section==0) {
return sectionOneCount;
}
else {
return sectionTwoCount;
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if(section == 0) {
return @"Section One Title";
}
else {
return @"Section Two Title";
}
}
这是我的 cellForRowAtIndexPath 方法:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"MainCell";
ProfileTableViewCell *cell = [mainTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[ProfileTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.label1.text = [[items objectAtIndex:indexPath.row] valueForKey:@"label1"];
cell.label2.text = [[items objectAtIndex:indexPath.row] valueForKey:@"label2"];
return cell;
}
关于我在这里做错了什么有什么想法吗?谢谢!
附:这是我正在使用的一些示例数据。我只有两个可能的部分,每种类型一个(在本例中为红色和蓝色)。我有一个名为 items 的主数组(如您在我的 cellForRowAtIndexPath 方法中所见)。
{
"parentArray": {
"id": 5,
"items": [
{
"type": "red",
"title": "RedItem1"
},
{
"type": "red",
"title": "RedItem2"
},
{
"type": "blue",
"title": "BlueItem1"
},
{
"type": "blue",
"title": "BlueItem2"
},
{
"type": "blue",
"title": "BlueItem3"
}
]
}
}
【问题讨论】:
-
您需要在
if-else或switch块中使用indexPath.section来为不同的部分执行不同的逻辑。检查类似的问题:UITableView, how do I know what Section during cellForRowAtIndexPath? -
谢谢,我已经对此进行了一段时间的研究,到目前为止,我所看到的答案都没有适用于我的代码。我会继续寻找。谢谢!
-
另外,即使我确实使用了我最初尝试的 if-else 语句,我的所有数据都存储在一个数组中。所以我不确定应该如何处理。
-
hm...好吧,那么...你怎么知道数组中的哪个对象是哪个部分的?相反,你要去做什么?因为一个包含 N 个字典或 N 个数组的数组可以保存 N 个可能部分的值
-
他们按顺序出来了。所以第 1 节的所有内容都首先出现,我有一个递增的全局整数。然后第 2 节的所有结果都出来了,我还有另一个全局 int。然后我将这两个整数包含在我的 numberOfRowsInSection 方法中。
标签: ios objective-c uitableview