iOS 获取自定义cell上按钮所对应cell的indexPath.row的方法

本文介绍如何在UITableView或UICollectionView的自定义cell中设置一个按钮,并通过两种方法获取点击该按钮时所在cell的位置(indexPath.row)。一种是直接通过发送者(sender)获取cell,另一种是在加载cell时设置Tag。

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

  在UITableView或UICollectionView的自定义cell中创建一button,在点击该按钮时知道该按钮所在的cell在UITableViewUICollectionView中的行数。就是cell的 indexPath.row,下面以UITableView为例:

    有两种方法:
-(IBAction):(id)sender
{

   1. 第一种方法,这个方便一点点,不用设置tag。

   NSLog(@"MyRow:%d",[self.table indexPathForCell:((TableViewCell*)[[sender   superview]superview])].row);
 2. 第二种方法,这个需要加载cell时设置tag.不过也很方便。
    NSLog(@"MyRow:%d",((TableViewCell*)[[sender superview]superview]).tag);
   
}
    在UITableViewDataSource的协议方法里需要添加的代码:
-(UITableViewCell *)tableView:(UITableView *)tableView
        cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //删除cell.contentView中所有内容,避免以下建立新的重复
    int i = [[cell.contentView subviews] count] - 1;
    for(;i >= 0 ; i--)
    {
         [[[cell.contentView subviews] objectAtIndex:i] removeFromSuperview];
    }

    //添加button
    UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
    [but setBackgroundImage:[UIImage imageNamed:@"delete.png"] forState:UIControlStateNormal];
    [but setFrame:CGRectMake(280, 10, 30, 30)];
    [but setAlpha:0.8];
    [but addTarget:self action:@selector(del:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:but];
    //设置Tag为cell 对应的indexPath row
    for(id view in subviews)
    {
         if([view isKindOfClass:[UIButton class]])
         {
             [view setTag:[indexPath row]];
             //[cell.contentView bringSubviewToFront:view];
         }
    }
}
//Button事件
-(void)del:(id)sender
{
    for(UITableViewCell *cell in visiblecells)
    {
        if(cell.tag == button.tag)
    {
    //button.tag就是对应的[indexPath.row

转载于:https://www.cnblogs.com/fwx2015/p/4899022.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值