本文转载自http://blog.csdn.net/reylen/article/details/47043571,顺便加了一些笔记
在通过 -tableView: viewForHeaderAtSection: 设置headerView,然后再去通过headerViewForSection取的时候 ,发现返回结果为nil;
究其原因
For a Header/Footer, we will take UITableViewHeaderFooterView and use the dequeueReusableHeaderFooterViewWithIdentifier method.1
换一种说法就是:
Header/Footer也要像UITableViewCell一样指定Identifier,否则你用headerViewForSection:方法来获取Head/Footer的结果只能为nil
eg:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{ static NSString *hIdentifier = @"hIdentifier";
UITableViewHeaderFooterView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:hIdentifier]; if(header == nil) {
header = [[[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:hIdentifier] autorelease]; UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(0,0,self.view.frame.size.width,40)]autorelease];
label.textColor = [UIColor blackColor];
[header addSubView:label];
}
NSArray*subview = [header subviews];
UILabel* label = nil;
for (id v in subview) {
if ([v isKindOfClass:[UILabel class]]) {
label = (UILabel *)v;
break;
}
}
if(label)
{ // update label info
label.text = @"label text";
label.tag = section;
}
return header;
}
那么在需要用到的地方可以通过如下获取到label;
UITableViewHeaderFooterView *headerView = [tableView headerViewForSection:indexPath.section];
NSArray*subview = [header subviews];UILabel* label = nil;for (id v in subview)
{
if ([v isKindOfClass:[UILabel class]]) {
label = (UILabel *)v;
break;
}
}
if(label)
{
// update label info
}