iOS tableViewCell添加button并获取点击事件

2020-08-07  本文已影响0人  Lee坚武
image.png

如图效果所示:废话不说下面是代码哦!

// 设置单元格,并添加查看按钮
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AdaptiveTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    // 传递数组模型
    cell.backgroundColor = [UIColor  clearColor];
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(cell.frame.size.width-90,15, 70.0f, cell.frame.size.height-UIBorder *1.5)];
    btn.layer.cornerRadius = 7.0;//2.0是圆角的弧度,根据需求自己更改
    [btn setBackgroundColor:LoginBtnColor];
    [btn setTitle:@"查看" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.titleLabel.font = fontLarge;
    [btn addTarget:self action:@selector(cellBtnClicked:event:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:btn];
    cell.model = self.dataSource[indexPath.row];
    return cell;
}

- (void)cellBtnClicked:(id)sender event:(id)event {

    NSSet *touches =[event allTouches];

    UITouch *touch =[touches anyObject];

    CGPoint currentTouchPosition = [touch locationInView:_tableView];

    NSIndexPath *indexPath= [_tableView indexPathForRowAtPoint:currentTouchPosition];

    if (indexPath!= nil) {

        NSLog(@"%zd",indexPath.row);

    }

}

上一篇 下一篇

猜你喜欢

热点阅读