美文网首页
用运行时在Cell给UIButton传参数

用运行时在Cell给UIButton传参数

作者: mjf | 来源:发表于2016-07-05 10:34 被阅读0次

对于一个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的控件中。

相关文章

网友评论

      本文标题:用运行时在Cell给UIButton传参数

      本文链接:https://www.haomeiwen.com/subject/apehjttx.html