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

iOS中给UIButton通过runtime给响应方法传参

2015-09-18 15:31 295 查看
本文着重讲解通过runtime给button关联对象,从而实现给button的响应方法传参数

我们通过
addTarget: action:forControlEvents:方法给UIButton添加响应事件,形如:

[btn addTarget:self action:@selector(btnTouhced:) forControlEvents:UIControlEventTouchUpInside];


btnTouched就是响应方法。

那么问题来了,想要给这个方法btnTouched传个参数怎么实现?

1.最基本的传参

- (void)initButton
{
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 20)];
btn.tag = 10;
[btn addTarget:self action:@selector(btnTouhced:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:btn];
}

- (void)btnTouhced:(UIButton *)btn
{
NSLog(@"%d",btn.tag);
}


这就实现了把整数10传过去了。

但是,如果想要传的参数是一个对象怎么办?例如要传NSString. 前面说的传参形式就不能满足要求了。

下来介绍一种利用runtime机制来实现传参,你可以不需要知道runtime关联原理,就可以使用。如果想了解runtime关联原理请参考:OC-关联

先了解runtime关联的三个方法:

创建关联

objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)

获取关联

objc_getAssociatedObject(id object, const void *key)

断开关联

objc_removeAssociatedObjects(id object)

直接上代码:

- (void)installTickButtonOnCell:(ZLPhotoPickerCollectionViewCell *)cell
AtIndex:(NSIndexPath *)indexPath
{
UIButton *tickButton = [[UIButton alloc] init];
tickButton.frame = CGRectMake(cell.frame.size.width - 28, 5, 21, 21);
[tickButton setBackgroundColor:[UIColor clearColor]];
//runtime 关联对象
objc_setAssociatedObject(tickButton, @"tickBtn", indexPath, OBJC_ASSOCIATION_ASSIGN);
[tickButton addTarget:self action:@selector(tickBtnTouhced:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:tickButton];
}
- (void)tickBtnTouhced:(UIButton *)btn
{
//runtime 获取关联的对象
NSIndexPath * indexPath = objc_getAssociatedObject(btn, @"tickBtn");
NSLog(@"tickBtnTouhced----%d",indexPath.item);
}


这个例子是传递了一个NSIndexPath对象。

就这么简单。over!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: