我有一个UITableView
,其中包含许多sections
,每个部分只有一行。
我想要做的是,当我点击特定单元格时,应该更改与单元格对应的标题的标题。
我已使用-tableView:viewForHeaderInSection:
如何在-tableView:didSelectRowAtIndexPath:
方法中获取行标题?
答案 0 :(得分:7)
您可以获取所选索引的标题视图,如:
UIView *headerView=[deviceTable headerViewForSection:indexPath.section];
然后通过循环遍历来获取来自headerView的孩子。似乎
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;
答案 1 :(得分:4)
我建议同时实施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];
}
答案 2 :(得分:3)
快速解决方案:
let sectionHeaderView = table.headerViewForSection(indexPath.section)
let sectionTitle = sectionHeaderView?.textLabel?.text
答案 3 :(得分:0)
只需使用节标题的数据源即可。所以无论你有NSArray
,你都拥有
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
只需在didSelectRowAtIndexPath中使用它:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
...
NSString *titleForHeader = [myHeaderTitleArray objectAtIndex:indexPath.section];
}
答案 4 :(得分:0)
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
答案 5 :(得分:-1)
您可以使用以下方式获取部分索引:
indexpath.section
使用部分索引,您只需复制-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
中的内容即可获得部分标题。