从tableViewCell类获取indexPath

时间:2014-03-16 15:01:01

标签: ios button uitableview

我有一个连接到我的UITableViewCell类的按钮(动作)。如何从tableViewCell类中获取tableView的indexPath?

@implement myTableViewCell

-(IBAction)buttonPressed{
    // Do something to get indexPath?
}

4 个答案:

答案 0 :(得分:2)

在CustomCell.h中

@property (nonatomic, strong) UIButton *btn;
tableView dataSource文件中的

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"Cell";
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
         cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
         [cell.btn addTarget:self action:@selector(buttonPressed:event:) forControlEvents:UIControlEventTouchUpInside];
}

//button action
-(void)buttonPressed:(UIControl *)sender event:(id)event{
   UITouch *touch = [[event allTouches] anyObject];
   CGPoint touchPos = [touch locationInView:self.tableView];
   NSIndexPath *indexPath = [self.tableView  indexPathForRowAtPoint:touchPos];
   if(indexPath != nil){
       //to do with indexPath 
   }
}

//单元格类中的按钮操作

- (void)buttonPressed:(UIButton *)btn event:(id)event{
    UIView *superView = [btn superview];
    while (superView && ![superView isKindOfClass:[UITableView class]]) {
        superView = [superView superview];
    }

    if ([superView isKindOfClass:[UITableView class]]) {
        UITableView *tableView = (UITableView *)superView;
        UITouch *touch = [[event allTouches] anyObject];
        CGPoint touchPos = [touch locationInView:tableView];
        NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPos];
        if(indexPath != nil){
            NSLog(@"tableView.row:%d", indexPath.row);
        }
    }
}

答案 1 :(得分:0)

就像这个answer

CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];

答案 2 :(得分:0)

使用发件人向您的按钮添加操作:

    [btn addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

然后:

- (void) buttonPressed:(id)sender{
    CGPoint hitPoint = [sender convertPoint:CGPointZero toView:tableView];
    NSIndexPath *hitIndex = [tableView indexPathForRowAtPoint:hitPoint];

}

答案 3 :(得分:0)

  1. 从单元格中获取表格。把它放在牢房里面

    - (UITableView*)tableView {
        if (tableView == nil) {
            tableView = (UITableView*)self.superview;
            while (tableView && ![tableView isKindOfClass:[UITableView class]]) {
                tableView = (UITableView*)tableView.superview;
            }
        }
        return tableView;
    }
    
  2. IBAction中的
  3. 请求索引路径

    NSIndexPath *p = [self.tableView indexPathForCell:self];
    
  4. TADA;)