您的位置:首页 > 产品设计 > UI/UE

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

2013-05-28 14:45 351 查看
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);

}

这样就可以绕过之前的阻碍继续获取当前点击行数了.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐