我正在尝试使用此代码获取节标题 View :
[tableView headerViewForSection:indexPath.section];
但是这段代码总是返回零。 你能给我一些例子来从 TableView 中获取节标题 View 吗? 这是我的 viewForHeader 实现:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
DynamicHeader *headerView = [[DynamicHeader alloc] init];
headerView.frame = CGRectMake(0, 0, 320, 40);
UILabel *headerLbl = [[UILabel alloc] init];
headerLbl.frame = CGRectMake(10, 10, 300, 20);
if(((SectionViewController *)sharedInstance.currentViewController).currentSectionType == 25)
{
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"minus.png"]];
imgView.frame = CGRectMake(285, 14.5, 16, 13);
[headerView addSubview:imgView];
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:sharedInstance action:@selector(headerTap:)];
[headerView addGestureRecognizer:recognizer];
headerView.tableView = tableView;
headerView.heightForRows = 95;
headerView.isOpen = YES;
}
headerLbl.text = [[[[[((SectionViewController *)sharedInstance.currentViewController).responseDictionary valueForKey:DATA_PARAMETER] valueForKey:SECTION_TABLE_PARAMETER] objectAtIndex:section] valueForKey:TABLE_SECTION_HEADER] capitalizedString];
[headerView addSubview:headerLbl];
return headerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if((DynamicHeader *)[tableView headerViewForSection:indexPath.section] != nil)
{
return ((DynamicHeader *)[tableView headerViewForSection:indexPath.section]).heightForRows;
}
else
{
return 95;
}
}
- (void)headerTap: (UITapGestureRecognizer *)recognizer
{
DynamicHeader *view = (DynamicHeader *)[recognizer view];
if(view.isOpen)
{
view.heightForRows = 0;
}
else
{
view.heightForRows = 95;
}
view.isOpen = !view.isOpen;
[view.tableView beginUpdates];
[view.tableView endUpdates];
}
最佳答案
很老的问题,但也许解决方案对其他人也有帮助...
只有在需要时(例如,它们在表格 View 内容区域中可见),UITableView 才会创建单元格、页眉和页脚 View 。
如果单元格、页眉或页脚 View 在表格 View 中不可见,则调用“cellForRowAtIndexPath:”、“headerViewForSection:”或“footerViewForSection:' 可能会返回 'nil'。 (有关此行为的文档,请参阅 UITableView.h。唯一的异常(exception)是,该 View 尚未被 TableView 回收)
当然,您可以通过直接调用负责的委托(delegate)方法来创建任何 TableView subview ,但 UITableView 不会自己这样做。
因此访问单元格、页眉或页脚 View 的解决方案是首先使其在 TableView 中可见。
标题 View 示例:
CGRect sectionHeaderRect = [self.tableView rectForHeaderInSection:groupSectionIndex];
[self.tableView scrollRectToVisible:sectionHeaderRect
animated:NO];
// Let the tableview load the needed views
dispatch_async(dispatch_get_main_queue(), ^{
UITableViewHeaderFooterView* groupSectionHeaderView = [self.tableView headerViewForSection:sectionIndex];
// Use groupSectionHeaderView
});
关于ios - 如何从 UItableView 获取节标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20882561/