UIButton 点击时无法附带自身参数的解决办法

UIButton的 taget函数只能是 不带参数或者带一个默认UIButton类型的参数.当把UIButton加入table的时候获取点击时候的行数就是个问题.

目前有两个方法来处理:

1:用UIButton自身的tag    

也就是说在创建UIButton的时候设置tag为tableview的index.row.这样在回调函数里面根据tag就可以处理.但是这个方法有个弊端就是如果tag被用来做tableview的动态加载标示,那就用第二种方法去解决了

        示例

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d", indexPath.row];//这里按照每个row来标示cell,所以每个cell都是独立的,没有复用,数量少的时候可以这么处理

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];


   if(!cell)

    {

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];

    }


UIButton *btnBuy  = (UIButton*)[cell viewWithTag:indexPath.row];

    if(!btnBuy)

    {

XXXXX

btnBuy.tag =indexPath.row;

  [btnBuy addTarget:self action:@selector(onClickBuy:) forControlEvents:UIControlEventTouchUpInside];

}

[btnBuy setImage:XXXX];

return cell;

}

-(void)onClickBuy:(UIButton*)btn

{

    NSLog(@"点击了第%d",btn.tag);

}


以上这种就可以获取到当前点击的行数.

2:复用cell的情况下的解决办法:

解决办法其实就给uibutton增加一个子类view,设置子类view的tag

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

NSString *CellIdentifier = @"Cell";//注意这里这样写就是复用cell

     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];


   if(!cell)

    {

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];

    }


UIButton *btnBuy  = (UIButton*)[cell viewWithTag:4000];

    if(!btnBuy)

    {

XXXXX

btnBuy.tag =4000;

  [btnBuy addTarget:self action:@selector(onClickBuy:) forControlEvents:UIControlEventTouchUpInside];

UIView *tagView = [[UIView alloc]init];

        tagView.tag = indexPath.row;

        [btnBuy addSubview:tagView];

        [tagView release];


}

[btnBuy setImage:XXXX];

return cell;

}

-(void)onClickBuy:(UIButton*)btn

{

    UIView *tagView = [[btn subviews] objectAtIndex:0];

    NSLog(@"点击了第%d",tagView.tag);

}


这样就可以绕过之前的阻碍继续获取当前点击行数了.




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值