用运行时在Cell给UIButton传参数

对于一个CollectionView而言,多个Cell,而每个cell都有一样的按钮。那么怎么在生成按钮时给每个按钮传递indexPath.row的参数给按钮,让每次响应UIControlEventTouchUpInside又能获到呢?此时可以考虑运行时,如下:

//获取参数,object实参指定为按钮,key是@selector(paramValue:)对象

- (NSNumber *)paramValue:(id)object

{

return objc_getAssociatedObject(object, _cmd);

}

//设置参数,object实参指定为按钮,key是@selector(paramValue:)对象

- (void)setparamValue:(NSNumber *)value object:(id)object

{

objc_setAssociatedObject(object, @selector(paramValue:), value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

}

//构造按钮并传递index.row

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

UIButton* collectButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];

[collectButton addTarget:self action:@selector(clickCollect:) forControlEvents:UIControlEventTouchUpInside];

[self setparamValue:@(indexPath.row) object:collectButton];

}

//响应方法获取index.row区别不同的按钮

-(void)clickCollect:(UIButton*)button

{

NSNumber *number = [self paramValue:button]

}

以上同样可以运用在tableviewcell的控件中。


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容