【问题标题】:get the title of a tableview titleForHeaderInSection获取 tableview 的标题 titleForHeaderInSection
【发布时间】:2012-10-10 01:11:52
【问题描述】:

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

【问题讨论】:

    标签: objective-c ios uitableview


    【解决方案1】:

    将节的标题存储在数组中,

    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]);
    

    【讨论】:

    • 谢谢,我会在答案中发布代码,但我在手机上。
    【解决方案2】:

    好吧,UITableView 似乎确实应该为您提供对此的访问,但我没有找到任何东西......我认为实现它的最简单方法是创建一个数组(我称之为mySectionTitles 并假设它是一个属性)与您的部分标题,然后在 didSelectRowAtIndexPath 中调用 [self.mySectionTitles objectAtIndex:indexPath.section] 并使用返回的字符串做任何您想做的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-05
      • 1970-01-01
      • 2014-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多