我有一个 UITableView,我在其中添加了一个 UIButton 作为每个单元格的附属 View 。请注意,我将按钮的标签设置为当前行以供将来使用。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
if(cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cellButton = [UIButton buttonWithType:UIButtonTypeCustom];
cellButton.frame = CGRectMake(0, 0, 30, 30);
[cellButton setBackgroundImage:[UIImage imageNamed:@"cellButton.png"] forState:UIControlStateNormal];
[cellButton addTarget:self action:@selector(cellButtonAction:) forControlEvents:UIControlEventTouchUpInside];
cellButton.tag = indexPath.row; // <= Will use this in the next method
cell.accessoryView = cellButton;
}
//Load cell with row based data
return cell;
}
现在,当这些按钮之一被点击时,我需要对单元格进行更改。所以我实现了 cellButtonAction,我在其中使用标签取回单元格:
-(void)editCommentButtonAction:(id)sender
{
UIButton *button = sender;
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag inSection:0];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
[self makeChangesToCell:cell];
}
但这似乎是一个非常迂回的方式。有没有更简洁的方法来做到这一点?
最佳答案
所以假设按钮直接在 contentView
中:
向“
sender
”(即按钮)询问其父 View ,即单元格的 contentView向那个 View 请求它的
superView
,也就是单元格向 tabview 询问此单元格的索引:
- (NSIndexPath *)indexPathForCell:(UITableViewCell *)cell
编辑:实际上,我现在使用的是通用方法或函数,它只是沿着 super View 向上移动,寻找“KindOf”、UITableViewCell 或 UICollectionViewCell 的 View 。像冠军一样工作!
Swift 中的代码:
func containingUITableViewCell(tableView: UITableView, var view: UIView) -> (UITableViewCell, NSIndexPath)? {
while let v = view.superview {
view = v
if view.isKindOfClass(UITableViewCell.self) {
if let cell = view as? UITableViewCell, let indexPath = tableView.indexPathForCell(cell) {
return (cell, indexPath)
} else {
return nil
}
}
}
return nil
func containingUICollectionViewCell(collectionView: UICollectionView, var view: UIView) -> (UICollectionViewCell, NSIndexPath)? {
while let v = view.superview {
view = v
if view.isKindOfClass(UICollectionViewCell.self) {
if let cell = view as? UICollectionViewCell, let indexPath = collectionView.indexPathForCell(cell) {
return (cell, indexPath)
} else {
return nil
}
}
}
return nil
}
关于ios - 如何从 UIButton 操作方法获取 UITableViewCell 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11669645/