定制UITableViewCell的事件响应处理

在定制的UITableViewCell中,如果需要对cell中的控件添加事件响应,就要想办法把cell的indexPath传递给响应函数。下面是一个相对方便且耦合度低的方法。UICollectionView同样适用。

假设定制的cell类名为MyUITableViewCell,上面添加了一个按钮myButton,需要在点击MyButton的响应函数中获取cell的indexPath。

解决思路是这样:

  1. 在MyUITableViewCell中添加一个指向UITableView的指针,需要获取indexPath时,通过指针向tableView查询。

  2. 在MyUITableViewCell中添加一个block属性,在实例化MyUITableViewCell时,给block赋值。在MyUITableViewCell的实现中响应MyButton的点击事件,在响应函数中调用block。

下面来实现一下:

1 在MyUITableViewCell的@inderface中添加两个属性,一个是UITableView指针,一个是响应事件block:


typedef void(^OnMyButtonClick)(NSIndexPath *indexPath);

@interface MyUITableViewCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UIButton *myButton;

@property (weak, nonatomic)UITableView *tableView;
@property (nonatomic, strong)OnMyButtonClick onMyButtonClick;
@end

2 在MyUITableViewCell的实现中实现myButton的点击响应


#import "MyUITableViewCell.h"

@implementation MyUITableViewCell


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (IBAction)onClickMyButton:(id)sender {
    NSIndexPath *indexPath = [[self tableView] indexPathForCell:self];
    if (_onMyButtonClick) {
        _onMyButtonClick(indexPath);
    }
}

@end


3 在实例化MyUITableViewCell之后,给两个属性赋值:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    MyUITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    if(cell){
        __weak typeof(self) weakSelf = self;
        cell.tableView = tableView;
        cell.onMyButtonClick = ^(NSIndexPath *indexPath){
            [weakSelf onMyButtonClick:indexPath];
        }
    }
    return cell;
}

其中[weakSelf onMyButtonClick];调用的是真正的处理点击的方法,实现在对应的viewController中。

有一种做法是将indexPath.row赋值给myButton.tag,点击时直接从tag中取出row的值。这样比较简单,适用于tableViewCell顺序不可变,且只有一个section的情况。

还有一种做法是在MyUITableViewCell中添加一个controller的属性,在MyUITableViewCell实现的响应函数中通过controller调用真正的事件处理方法。这样做的缺点是MyUITableViewCell需要依赖对应controller的实现,耦合度稍微高了一点。

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

推荐阅读更多精彩内容

  • iOS网络架构讨论梳理整理中。。。 其实如果没有APIManager这一层是没法使用delegate的,毕竟多个单...
    yhtang阅读 10,652评论 1 23
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,313评论 30 472
  • 2017.02.22 可以练习,每当这个时候,脑袋就犯困,我这脑袋真是神奇呀,一说让你做事情,你就犯困,你可不要太...
    Carden阅读 5,192评论 0 1
  • 今天看了《谁的青春不迷茫》的宣传,感慨自然很多。最后最多的竟然是对于《变形记》的感触。 对于这个电影,包括这本书,...
    鸵鸟变凤凰阅读 3,564评论 2 1
  • 六 一承载了你 我 他 她 回忆折一只千纸鹤写上几句话语那可能是父辈的足记2017 6 1吕圣莲老师告诉你只是俯下...
    优才作文吕圣莲阅读 1,293评论 0 0