您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS Block 用法:自訂 UITableViewCell 按鈕事件回傳

編輯:iOS 開發綜合

在自訂 UITableViewCell 中,若 Cell 內有多個按鈕,需要將點擊事件回傳給列表控制器,Block 是一種靈活的解法。相比 delegate,Block 能讓事件處理更集中,也更容易在建立 Cell 時直接設定回呼。

1. 在 Cell 中宣告 Block

於自訂 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;

2. 在 Cell 中觸發 Block

當按鈕被點擊時,執行對應 Block:

if (self.addGoodNumBlock) {
    self.addGoodNumBlock(self);
}

3. 在列表控制器中設定 Block

在配置 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];
    }
};

4. 使用建議

使用 Block 回傳 Cell 事件時,應注意避免循環引用。若 Block 中強引用控制器,而控制器又持有 Cell,可能會造成記憶體無法釋放。必要時可使用 weak 或搭配資料源更新方式處理。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved