【发布时间】:2011-09-17 04:18:13
【问题描述】:
我有一个表视图,其中包含两个操作,第一个我使用委托 didSelectRowAtIndexPath,第二个我想在我的单元格上的按钮上使用一个操作来做其他事情。我的问题是我没有成功获得 indexpath ?这样做的最佳做法是什么。
【问题讨论】:
标签: xcode uitableview nsindexpath
我有一个表视图,其中包含两个操作,第一个我使用委托 didSelectRowAtIndexPath,第二个我想在我的单元格上的按钮上使用一个操作来做其他事情。我的问题是我没有成功获得 indexpath ?这样做的最佳做法是什么。
【问题讨论】:
标签: xcode uitableview nsindexpath
如果你已将按钮添加到单元格中,
[cell.contentView addSubview:button];
那么,你可以得到索引路径,
- (void)onButtonTapped:(UIButton *)button {
UITableViewCell *cell = (UITableViewCell *)button.superview.superview;
NSIndexPath *indexPath = [tableView indexPathForCell:cell];
// Go ahead
}
【讨论】:
我正在使用这个解决方案——使用点获取单元格的索引路径
CGPoint center= [sender center];
CGPoint rootViewPoint = [[sender superview] convertPoint:center toView:_tableView1];
NSIndexPath *indexPath = [_tableView1 indexPathForRowAtPoint:rootViewPoint];
NSLog(@"%@",indexPath);
它的工作完美
【讨论】:
superView.superView更合适
这是自定义按钮的完整代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
CustomCellFilter *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {cell = [[CustomCellFilter alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];}
//configure your cell here
cell.titleLabel.text = @"some title";
//add button
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
resetButton.frame = CGRectMake(40, 10, 18, 18);
[resetButton addTarget:self action:@selector(onButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
[resetButton setImage:[UIImage imageNamed:@"someimage.png"] forState:UIControlStateNormal];
[cell.contentView addSubview:myButton];
//afterwards return the cell
return cell;
- (void)onButtonTapped:(UIButton *)button {
UITableViewCell *cell = (UITableViewCell *)button.superview.superview;
NSIndexPath *indexPath = [filterTable indexPathForCell:cell];
NSLog(@"%@", indexPath);
//use indexPath here...
}
【讨论】:
如果您使用的是集合视图,您可以使用 Yogesh 方法,但将 indexPathForRowAtPoint 更改为 indexPathForItemAtPoint,如下所示:
CGPoint center= [sender center];
CGPoint rootViewPoint = [[sender superview] convertPoint:center toView:_tableView1];
NSIndexPath *indexPath = [_tableView1 indexPathForRowAtPoint:rootViewPoint];
NSLog(@"%@",indexPath);
【讨论】:
如果您的按钮被移动或 Apple 更改了附件视图的视图层次结构,此方法会向上查找 UITableViewCell:
- (void)tapAccessoryButton:(UIButton *)sender {
UIView *parentView = sender.superview;
// the loop should take care of any changes in the view heirarchy, whether from
// changes we make or apple makes.
while (![parentView.class isSubclassOfClass:UITableViewCell.class])
parentView = parentView.superview;
if ([parentView.class isSubclassOfClass:UITableViewCell.class]) {
UITableViewCell *cell = (UITableViewCell *) parentView;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
[self tableView:self.tableView accessoryButtonTappedForRowWithIndexPath:indexPath];
}
}
【讨论】: