1

我的 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;
}
4

2 回答 2

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]);
于 2012-10-10T02:54:17.743 回答
1

好吧,看起来 UITableView 应该为您提供对此的访问权限,但我没有找到任何东西......我认为实现这一点的最简单方法是创建一个数组(我将其称为 mySectionTitles 并假设它是一个属性)与您的部分标题,然后在 didSelectRowAtIndexPath 中调用[self.mySectionTitles objectAtIndex:indexPath.section]并使用返回的字符串执行任何您想要的操作。

于 2012-10-10T02:42:06.147 回答