给定制的UITableViewCell里的控件点击设置代理

功能:

界面用TableView实现,其中有两个定制的cell,cell里放置了几个SDWebImageView并添加点击手势来捕获事件。开始写的时候,只是在定制Cell类里定义了界面,然后在引用的Controller里添加手势。发现代码重复了,就换用Delegate实现,整洁多了。

图片(App:爱飞扬旅游):

请输入图片描述

实现

界面用一个tableview实现,上面的图片是tableview的HeadView。Cell里的图片可以点击,push到下个界面,点击事件绑定在Cell的类里。在引用cell的类里给cell设置tag,区分点击事件的来源。

Cell的代码(部分):

.h文件

@class StragetyMainPageCell;

@protocol MainPageCellDelegate <NSObject>
- (void)ImageTap1:(StragetyMainPageCell *)cell;
- (void)ImageTap2:(StragetyMainPageCell *)cell;
- (void)ImageTap3:(StragetyMainPageCell *)cell;
- (void)ImageTap4:(StragetyMainPageCell *)cell;
- (void)ImageTap5:(StragetyMainPageCell *)cell;
- (void)moreButtonClick:(StragetyMainPageCell *)cell;
@end
@interface StragetyMainPageCell : UITableViewCell
@property (assign, nonatomic) id<MainPageCellDelegate> delegate;
@end

.m文件: 给其中一个图像添加点击事件:

UITapGestureRecognizer *imageTap1 = [[UITapGestureRecognizer alloc] initWithTarget:self
 action:@selector(ImageTap1)]; [self.image1 addGestureRecognizer:imageTap1];

具体的点击事件:

- (void)ImageTap1
{
 if (_delegate && [_delegate respondsToSelector:@selector(ImageTap1:)]) {
 [_delegate ImageTap1:self];
}
}
就可以触发在引用类里的代理方法了。一开始不明白为什么代理方法的第一个参数要是定义代理的类,这边可以通过这个cell类的tag,来区分不同点击事件的来源。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章