我有一个UITableView
,它有许多sections
,每个section只有1行。
我想要实现的是,当我点击某个cell时,与之对应的header标题应该被更改。
我已经使用-tableView:viewForHeaderInSection:
来设置了section header。
在-tableView:didSelectRowAtIndexPath:
方法中,我该如何获取行头标题呢?
我有一个UITableView
,它有许多sections
,每个section只有1行。
我想要实现的是,当我点击某个cell时,与之对应的header标题应该被更改。
我已经使用-tableView:viewForHeaderInSection:
来设置了section header。
在-tableView:didSelectRowAtIndexPath:
方法中,我该如何获取行头标题呢?
UIView *headerView=[deviceTable headerViewForSection:indexPath.section];
for(UIView *view in headerView.subviews)
{
if ([v isKindOfClass:[UILabel class]])
{
UILabel *label=(UILabel *)v;
NSString *text=label.text;
}
}
编辑: 正如Desdenova所建议的:
UITableViewHeaderFooterView *headerView=[deviceTable headerViewForSection:indexPath.section];
NSString *title=headerView.textLabel.text;
tableView:titleForHeaderInSection:
和tableView:viewForHeaderInSection:
(如果两者都实现,则iOS会优先选择viewForHeaderInSection:
)。然后,在你的tableView:viewForHeaderInSection:
实现中,使用标签创建视图,并使用tableView:titleForHeaderInSection:
的结果来填充它。- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
UIView *yourHeaderView;
UILabel *someLabel;
// set up the view + label
// if self doesn't implement UITableViewDelegate, you can use tableView.delegate
someLabel.text = [self tableView:tableView titleForHeaderInSection:section];
return yourHeaderView;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *titleForHeader = [self tableView:tableView titleForHeaderInSection:indexPath.section];
}
快速解决方案:
let sectionHeaderView = table.headerViewForSection(indexPath.section)
let sectionTitle = sectionHeaderView?.textLabel?.text
Swift 4:
let indexPath = IndexPath.init(row: 0, section: 0) // put here your row or section number..
let myHeaderView = tableView.headerView(forSection:indexPath.section)
let title = myHeaderView?.textLabel?.text
只需使用数据源作为部分标题。因此,无论您拥有的NSArray
中包含哪些字符串值
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
只需在didSelectRowAtIndexPath中使用它:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
...
NSString *titleForHeader = [myHeaderTitleArray objectAtIndex:indexPath.section];
}
您可以使用以下代码获取部分索引:
indexpath.section
有了章节索引,你可以简单地复制在-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
中的内容以获取章节标题。