获取tableview titleForHeaderInSection的标题

时间:2012-10-10 01:11:52

标签: objective-c ios uitableview

我的iOS 6应用程序中有4个分段表。这些表都有我在titleForHeaderInSection中设置的标题。我想知道如何在didSelectRowAtIndexPath中使用NSLog访问此标题。我看到我在警报中点击的行的字符串值,但我也想看tableview部分的标题。我不知道该怎么做。

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

NSMutableArray *sectionArray = [self.arrayOfSections objectAtIndex:indexPath.section];

UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
NSString *cellText = selectedCell.textLabel.text;

NSLog(@"Selected Cell: %@", cellText);

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Selected a row" message:[sectionArray objectAtIndex:indexPath.row] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}


- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{

NSString *result = nil;

if ([tableView isEqual:self.myTableView] && section == 0) {

    myTableView.tableHeaderView.tag = FROZEN;
    result = @"Frozen";

} else if ([tableView isEqual:self.myTableView] && section == 1) {

    myTableView.tableHeaderView.tag = FRUIT;
    result = @"Fruit";

}
else if ([tableView isEqual:self.myTableView] && section == 2) {

    myTableView.tableHeaderView.tag = SALADS;
    result = @"Salads";

} else if ([tableView isEqual:self.myTableView] && section == 3) {

    myTableView.tableHeaderView.tag = VEGETABLES;
    result = @"Vegetables";
}

return result;
}

2 个答案:

答案 0 :(得分:3)

将部分的标题存储在数组中,

NSArray *sectionTitles = [NSArray arrayWithObjects:@"Frozen", @"Fruit", @"Salads", @"Vegetables", nil];

并将您的titleForHeaderInSection方法修改为

- (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSString *result = [sectionTitles objectAtIndex:section];
//....
return result;
}

didSelectRowAtIndexPath修改为,

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//...
NSLog(@"Header title: %@",  [sectionTitles objectAtIndex:indexPath.section]);
//...
}

另一种选择是在didSelectRowAtIndexPath

中使用以下方法
NSLog(@"Header title: %@",  [self tableView:tableView titleForHeaderInSection:indexPath.section]);

答案 1 :(得分:1)

嗯,看起来UITableView似乎应该为你提供访问权限,但我找不到任何东西......我认为实现这个的最简单方法就是创建一个数组(我称之为数组) mySectionTitles并假设它是一个属性)与你的节标题然后,在didSelectRowAtIndexPath中,调用[self.mySectionTitles objectAtIndex:indexPath.section]并用返回的字符串做任何你想做的事。