点击事件的实现并不难,下面将来介绍两种方法。
第一种方法——代理
1.1、首先在自定义的cell的.h文件中定义协议及相关属性
/*定义一个协议来区分表格的点击事件和表格上按钮的点击事件*/
@protocol <span style="color:#ff0000;">customCellBtnClicked</span> <NSObject>
-(void)customBtnClicked:(NSInteger)cellRow;
@end
/*定义相关属性,记录点击的行数*/
@property(nonatomic,assign)id<customCellBtnClicked>cellDelegate;
@property(nonatomic,assign)NSInteger cellRow;
其次我们需要在自定义cell的.m文件中按钮的点击事件做相关处理
-(void)btnNClicked{
<span style="color:#ff0000;"> if (_cellDelegate != nil && [_cellDelegate respondsToSelector:@selector(customBtnClicked:)]) {
[_cellDelegate customBtnClicked:_cellRow];
}</span>
}
1.2、然后我们需要在主控制器的.m文件中遵循协议
1.3、同时还要在TableView的代理方法中让控制器成为自定义cell的代理,
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
<span style="color:#ff0000;"> cell.cellDelegate = self;
cell.cellRow = indexPath.row;</span>
return cell;
}
1.4、最后在当前的控制器实现自定cell的代理方法即可
/* 实现自定义cell的协议方法 */
-(void)customBtnClicked:(NSInteger)cellRow{
//在这里可以做相关处理
}
第二种方法——按钮成为属性在做处理
2.1、首先还是在自定义的cell的.h文件中声明属性
2.2、然后TableView的代理方法中为按钮添加点击事件
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString * identify = @"cell";
chooseDetailCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
[cell sizeToFit];
if (!cell) {
NSLog(@"------------");
}
cell.cellBtn.tag = indexPath.row;
<span style="color:#ff0000;">[cell.cellBtn addTarget:self action:@selector(cellBtnClicked:) forControlEvents:UIControlEventTouchUpInside];</span>
cell.cellBtn.selected = [self theSelectArrIsHaveCurrentAsset:[_fetchResult objectAtIndex:indexPath.row]];
return cell;
}