在定制的UITableViewCell中,如果需要對cell中的控件添加事件響應(yīng),就要想辦法把cell的indexPath傳遞給響應(yīng)函數(shù)。下面是一個相對方便且耦合度低的方法。UICollectionView同樣適用。
假設(shè)定制的cell類名為MyUITableViewCell,上面添加了一個按鈕myButton,需要在點(diǎn)擊MyButton的響應(yīng)函數(shù)中獲取cell的indexPath。
解決思路是這樣:
在MyUITableViewCell中添加一個指向UITableView的指針,需要獲取indexPath時,通過指針向tableView查詢。
在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)。