對(duì)于一個(gè)CollectionView而言,多個(gè)Cell踊兜,而每個(gè)cell都有一樣的按鈕旦事。那么怎么在生成按鈕時(shí)給每個(gè)按鈕傳遞indexPath.row的參數(shù)給按鈕青灼,讓每次響應(yīng)UIControlEventTouchUpInside又能獲到呢?此時(shí)可以考慮運(yùn)行時(shí)辽旋,如下:
//獲取參數(shù),object實(shí)參指定為按鈕浩嫌,key是@selector(paramValue:)對(duì)象
- (NSNumber *)paramValue:(id)object
{
return objc_getAssociatedObject(object, _cmd);
}
//設(shè)置參數(shù)檐迟,object實(shí)參指定為按鈕,key是@selector(paramValue:)對(duì)象
- (void)setparamValue:(NSNumber *)value object:(id)object
{
objc_setAssociatedObject(object, @selector(paramValue:), value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
//構(gòu)造按鈕并傳遞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];
}
//響應(yīng)方法獲取index.row區(qū)別不同的按鈕
-(void)clickCollect:(UIButton*)button
{
NSNumber *number = [self paramValue:button]
}
以上同樣可以運(yùn)用在tableviewcell的控件中码耐。