传递索引点击UITableViewHeader

时间:2016-08-12 13:45:19

标签: ios objective-c uitableview

我想点击UITableView标题时获取索引。现在我确实将UIGestureRecognizer添加到标题中:

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sectionTapped:)];

    UIView *headerView = [UIView new];
    headerView.backgroundColor = [UIColor grayColor];

    [headerView addGestureRecognizer:recognizer];

   // return [self.myTableView headerWithTitle:self.headers[section] totalRows:self.cells.count inSection:section];
    return headerView;
}

-(IBAction)sectionTapped:(id)sender{

    NSLog(@"tapped header");
}

是否有简单方法可以轻松传递Index部分?

2 个答案:

答案 0 :(得分:2)

headerview headerView.tag = section;设置标记 - (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sectionTapped:)]; UIView *headerView = [UIView new]; headerView.tag = section; headerView.backgroundColor = [UIColor grayColor]; [headerView addGestureRecognizer:recognizer]; // return [self.myTableView headerWithTitle:self.headers[section] totalRows:self.cells.count inSection:section]; return headerView; } -(IBAction)sectionTapped:(UITapGestureRecognizer *)recognizer{ NSLog(@"tapped header==%d",recognizer.view.tag); NSLog(@"tapped header == %ld", recognizer.view.tag); }

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let recognizer = UITapGestureRecognizer(target: self, action: Selector("sectionTapped:"))
let headerView = UIView()
headerView.tag = section
headerView.backgroundColor = UIColor.gray
headerView.addGestureRecognizer(recognizer)
// return [self.myTableView headerWithTitle:self.headers[section] totalRows:self.cells.count inSection:section];
return headerView
}

@IBAction func sectionTapped(_ recognizer: UITapGestureRecognizer) {
print("tapped header==\(recognizer.view?.tag)")
print("tapped header == \(recognizer.view?.tag)")
}

Swift 3及以上

2>&1

代替this

答案 1 :(得分:1)

添加标签:

recognizer.view.tag = section;

并获得:

- (IBAction)sectionTapped:(UITapGestureRecognizer *)recognizer{
    NSLog(@"tapped header %d", recognizer.view.tag);
}