在我的表viewForHeaderInSection
中,我正在设置变量_searchTerm
,使用类似的部分索引:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 21)];
headerView.backgroundColor = [UIColor colorWithRed:0.949 green:0.949 blue:0.949 alpha:1];
_searchTerm = [[[[_matchCenterData objectAtIndex:section] objectForKey:@"Top 3"] objectAtIndex:0]objectForKey:@"Search Term"];
return nil;
}
对于每个部分,我想在_searchTerm
中使用其各自的cellForRowAtIndexPath
变量,如下所示:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//load top 3 data
NSDictionary *currentSectionDictionary = _matchCenterData[indexPath.section];
NSArray *top3ArrayForSection = currentSectionDictionary[@"Top 3"];
//... code removed to brevity
// title of the item
cell.textLabel.text = _searchTerm;
}
这似乎不起作用,单元格textLabel显示为空白。可以在viewForHeaderInSection
中使用cellForRowAtIndexPath
中的变量,如果是这样,我做错了什么?
答案 0 :(得分:2)
首先,请考虑您在cellForRowAtIndexPath
中使用的任何内容随indexPath
的变化而变化,作为数据源的一部分。其次,不要初始化数据源数据viewForHeader
。在同一个位置初始化其余数据(其余_matchCenterData
)
所以,如果你有:
@property(strong,nonatomic) NSArray *matchCenterData;
然后还有......
@property(strong,nonatomic) NSArray *searchTerms; // notice the plural name
你在哪里:
self.matchCenterData = // whatever
然后还有(伪代码)......
for (each section in self.matchCenterData) {
[self.searchTerms addObject:the thing you were setting in viewForHeader]
现在,您的cellForRowAtIndexPath
可以正常处理这些额外的数据源数据......
cell.textLabel.text = self.searchTerms[indexPath.section];
顺便提一下,一个更好的数据源可能包括matchCenterData中的分段信息,而不是我在这里提出的稍微粗略的“并行阵列”的想法。
更为偶然的是,请注意我如何声明名为“foo”的属性,然后将其称为self.foo
,而不是_foo
。除了少数例外,这也是你应该采用的一种做法。
答案 1 :(得分:2)
不直接回答您的问题,但您可以通过将cell.textLabel.text
分配给数据源来实现所需的结果。
cell.textLabel.text = [[[[_matchCenterData objectAtIndex:indexPath.section] objectForKey:@"Top 3"] objectAtIndex:0]objectForKey:@"Search Term"];
现在,cell.textLabel.text
为空的可能原因是因为cellForRow
之前调用了viewForHeaderInSection
方法