本文着重讲解通过runtime给button关联对象,从而实现给button的响应方法传参数
我们通过 addTarget: action:forControlEvents:方法给UIButton添加响应事件,形如:
[btn addTarget:self action:@selector(btnTouhced:) forControlEvents:UIControlEventTouchUpInside];
btnTouched就是响应方法。
那么问题来了,想要给这个方法btnTouched传个参数怎么实现?
- (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); }
但是,如果想要传的参数是一个对象怎么办?例如要传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); }
就这么简单。over!