UITableView中添加UIButton按钮处理

这篇博客介绍了如何在UITableView中添加UIButton,并实现按钮点击事件的处理。通过为按钮设置标识符和监听事件,当用户点击时,可以触发指定的方法并根据点击位置获取相应的IndexPath。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    UIButton * accessoryDetailDisclosureButton;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
        
        [cell.textLabel setTextColor:[UIColor darkGrayColor]];
        [cell.detailTextLabel setTextColor:[UIColor darkGrayColor]];
        [cell.detailTextLabel setNumberOfLines:4];
        [cell.detailTextLabel setFont:[UIFont systemFontOfSize:12]];
        
        accessoryDetailDisclosureButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
        [accessoryDetailDisclosureButton setImage:[UIImage imageNamed:@"push.png"] forState:UIControlStateNormal];
        [accessoryDetailDisclosureButton setImage:[UIImage imageNamed:@"push_h.png"] forState:UIControlStateHighlighted];


// 加入button单击事件
        [accessoryDetailDisclosureButton addTarget:self action:@selector(accessoryDetailDisclosureButtonPress: event:) forControlEvents:UIControlEventTouchUpInside];
        
        accessoryDetailDisclosureButton.tag = indexPath.row+100;
    }
    else
    {
        accessoryDetailDisclosureButton = (UIButton *)[cell viewWithTag:indexPath.row+100];
    }
  UIImage *image = [UIImage imageNamed:@"Placeholder.png"];
    [cell.imageView setImage:image];

    cell.textLabel.text =@“”;
    cell.detailTextLabel.text =  @“”;
    // Configure the cell...
    cell.accessoryView = accessoryDetailDisclosureButton;
    
    return cell;
    
}

// 检查用户点击按钮时的位置,并转发事件到对应的accessory tapped事件

-(void)accessoryDetailDisclosureButtonPress:(id)sender event:(id)event
{
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:m_tableView];
    NSIndexPath *indexPath = [m_tableView indexPathForRowAtPoint:currentTouchPosition];
    if(indexPath != nil)
    {
        [self tableView:m_tableView didSelectRowAtIndexPath:indexPath];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

//自定义处理
}


类似效果:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值