min*_*pop 84 objective-c uitableview ios
我有一个tableview控制器,显示一行单元格.每个单元格有3个按钮.我已将每个单元格的标签编号为1,2,3.问题是我不知道如何找到按下按钮的单元格.我当前只在按下其中一个按钮时才收到发件人的标签.当按下按钮时,有没有办法获取单元格行号?
iwa*_*bed 278
你应该真的使用这种方法:
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
Run Code Online (Sandbox Code Playgroud)
Swift版本:
let buttonPosition = sender.convert(CGPoint(), to:tableView)
let indexPath = tableView.indexPathForRow(at:buttonPosition)
Run Code Online (Sandbox Code Playgroud)
这将indexPath根据按下的按钮的位置给你.然后,cellForRowAtIndexPath如果您需要单元格或indexPath.row需要行号,则只需调用.
如果你是偏执狂,你可以if (indexPath) ...在使用它之前检查,以防万一indexPath在表格视图中找不到该点.
如果Apple决定改变视图结构,那么所有其他答案都可能会破裂.
use*_*234 40
编辑:这个答案已经过时了. 请改用此方法
试试这个:
-(void)button1Tapped:(id)sender
{
UIButton *senderButton = (UIButton *)sender;
UITableViewCell *buttonCell = (UITableViewCell *)[senderButton superview];
UITableView* table = (UITableView *)[buttonCell superview];
NSIndexPath* pathOfTheCell = [table indexPathForCell:buttonCell];
NSInteger rowOfTheCell = [pathOfTheCell row];
NSLog(@"rowofthecell %d", rowOfTheCell);
}
Run Code Online (Sandbox Code Playgroud)
编辑:如果您使用的是contentView,请将其用于buttonCell:
UITableViewCell *buttonCell = (UITableViewCell *)senderButton.superview.superview;
Run Code Online (Sandbox Code Playgroud)
Ash*_*hok 18
我建议这种方式来获取具有任何自定义子视图的单元格的indexPath - (与iOS 7兼容以及所有以前的版本)
-(void)button1Tapped:(id)sender {
//- (void)cellSubviewTapped:(UIGestureRecognizer *)gestureRecognizer {
// UIView *parentCell = gestureRecognizer.view.superview;
UIView *parentCell = sender.superview;
while (![parentCell isKindOfClass:[UITableViewCell class]]) { // iOS 7 onwards the table cell hierachy has changed.
parentCell = parentCell.superview;
}
UIView *parentView = parentCell.superview;
while (![parentView isKindOfClass:[UITableView class]]) { // iOS 7 onwards the table cell hierachy has changed.
parentView = parentView.superview;
}
UITableView *tableView = (UITableView *)parentView;
NSIndexPath *indexPath = [tableView indexPathForCell:(UITableViewCell *)parentCell];
NSLog(@"indexPath = %@", indexPath);
}
Run Code Online (Sandbox Code Playgroud)
这也不需要self.tablview.
另外,请注意注释代码,如果您希望通过添加到自定义子视图的UIGestureRecognizer的@selector来实现相同的代码.
| 归档时间: |
|
| 查看次数: |
71156 次 |
| 最近记录: |