按下按钮获取UITableView单元格行我有一个tableview控制器,显示一行单元格。每个单元格有3个按钮。我已将每个单元格的标签编号为1,2,3。问题是我不知道如何找到按下按钮的单元格。我当前只在按下其中一个按钮时才收到发件人的标签。当按下按钮时,有没有办法获取单元格行号?
                    
                    
                3 回答
                            万千封印
                            
                                
                            
                        
                        
                                                
                    TA贡献1891条经验 获得超3个赞
你应该真的使用这种方法:
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
Swift版本:
let buttonPosition = sender.convert(CGPoint(), to:tableView)let indexPath = tableView.indexPathForRow(at:buttonPosition)
这将indexPath根据按下的按钮的位置给你。然后,cellForRowAtIndexPath如果您需要单元格或indexPath.row需要行号,则只需调用。
如果你是偏执狂,你可以if (indexPath) ...在使用它之前检查,以防万一indexPath在表格视图中找不到该点。
如果Apple决定改变视图结构,那么所有其他答案都可能会破裂。
                            慕哥9229398
                            
                                
                            
                        
                        
                                                
                    TA贡献1877条经验 获得超6个赞
试试这个:
-(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);}编辑:如果您使用的是contentView,请将其用于buttonCell:
UITableViewCell *buttonCell = (UITableViewCell *)senderButton.superview.superview;
                            慕后森
                            
                                
                            
                        
                        
                                                
                    TA贡献1802条经验 获得超5个赞
我建议这种方式来获取具有任何自定义子视图的单元格的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);}这也不需要self.tablview。
另外,请注意注释代码,如果您希望通过添加到自定义子视图的UIGestureRecognizer的@selector来实现相同的代码。
- 3 回答
 - 0 关注
 - 538 浏览
 
添加回答
举报
0/150
	提交
		取消
	