在自訂 UITableViewCell 中,若 Cell 內有多個按鈕,需要將點擊事件回傳給列表控制器,Block 是一種靈活的解法。相比 delegate,Block 能讓事件處理更集中,也更容易在建立 Cell 時直接設定回呼。
於自訂 Cell 的標頭檔中定義 Block 型別與屬性:
typedef void(^AddGoodNumBlock)(ShopingCartTableViewCell *cell);
typedef void(^ReduceGoodNumBlock)(ShopingCartTableViewCell *cell);
typedef void(^SelectGoodBlock)(ShopingCartTableViewCell *cell);
@property (strong, nonatomic) AddGoodNumBlock addGoodNumBlock;
@property (strong, nonatomic) ReduceGoodNumBlock reduceGoodNumBlock;
@property (strong, nonatomic) SelectGoodBlock selectGoodBlock;
當按鈕被點擊時,執行對應 Block:
if (self.addGoodNumBlock) {
self.addGoodNumBlock(self);
}
在配置 Cell 時,將事件處理邏輯指派給 Block:
cell.addGoodNumBlock = ^(ShopingCartTableViewCell *cell) {
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
NSDictionary *goodsDic = [self.dataSource objectAtIndex:indexPath.section];
NSArray *goodsArray = [goodsDic objectForKey:@"array"];
self.good = [goodsArray objectAtIndex:indexPath.row];
self.good.num = [cell.numTF.text intValue] + 1;
if ([self alertNum]) {
cell.numTF.text = [NSString stringWithFormat:@"%d", [cell.numTF.text intValue] + 1];
}
if (cell.checkboxBtn.selected) {
[self alertSelecedGoodNum];
[self alertSum];
}
};
使用 Block 回傳 Cell 事件時,應注意避免循環引用。若 Block 中強引用控制器,而控制器又持有 Cell,可能會造成記憶體無法釋放。必要時可使用 weak 或搭配資料源更新方式處理。