定制UITableViewCell的事件響應(yīng)處理

在定制的UITableViewCell中,如果需要對cell中的控件添加事件響應(yīng),就要想辦法把cell的indexPath傳遞給響應(yīng)函數(shù)。下面是一個相對方便且耦合度低的方法。UICollectionView同樣適用。

假設(shè)定制的cell類名為MyUITableViewCell,上面添加了一個按鈕myButton,需要在點(diǎn)擊MyButton的響應(yīng)函數(shù)中獲取cell的indexPath。

解決思路是這樣:

  1. 在MyUITableViewCell中添加一個指向UITableView的指針,需要獲取indexPath時,通過指針向tableView查詢。

  2. 在MyUITableViewCell中添加一個block屬性,在實例化MyUITableViewCell時,給block賦值。在MyUITableViewCell的實現(xiàn)中響應(yīng)MyButton的點(diǎn)擊事件,在響應(yīng)函數(shù)中調(diào)用block。

下面來實現(xiàn)一下:

1 在MyUITableViewCell的@inderface中添加兩個屬性,一個是UITableView指針,一個是響應(yīng)事件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的實現(xiàn)中實現(xiàn)myButton的點(diǎn)擊響應(yīng)


#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];調(diào)用的是真正的處理點(diǎn)擊的方法,實現(xiàn)在對應(yīng)的viewController中。

有一種做法是將indexPath.row賦值給myButton.tag,點(diǎn)擊時直接從tag中取出row的值。這樣比較簡單,適用于tableViewCell順序不可變,且只有一個section的情況。

還有一種做法是在MyUITableViewCell中添加一個controller的屬性,在MyUITableViewCell實現(xiàn)的響應(yīng)函數(shù)中通過controller調(diào)用真正的事件處理方法。這樣做的缺點(diǎn)是MyUITableViewCell需要依賴對應(yīng)controller的實現(xiàn),耦合度稍微高了一點(diǎn)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容