iOS block用法
最近在學習的過程中遇到一個問題,整個項目用UINavigationController作為根控制器,某一個表試圖控制器使用了自訂的UITableViewCell,該類cell有自訂的幾個按鈕,當點擊cell的任何一個按鈕時需要知道當前是哪個cell以及哪個按鈕被點擊然後做相應的事件響應(更改該行資料,頁面跳轉等),之前用過代理,這一次想換一種方式,所以選擇了用塊來代替,下面列出詳細步驟
1.在自訂的cell標頭檔中申明塊,並定義相應的塊類型
#import
@class ShopingCartTableViewCell;
//塊申明
typedef void(^reduceGoodNumS)(ShopingCartTableViewCell *);
typedef void(^addGoodNumS)(ShopingCartTableViewCell *);
typedef void(^selectGoodS)(ShopingCartTableViewCell *);
@interface ShopingCartTableViewCell : UITableViewCell
//相應的塊變數定義
@property (strong,nonatomic) reduceGoodNumS reduceGoodNumBlock;
@property (strong,nonatomic) addGoodNumS addGoodNumBlock;
@property (strong,nonatomic) selectGoodS selectGoodBlock;
@end
2.在使用自訂cell填充表格的地方,實現塊功能,這裡以添加商品數量為例,減少商品數量和選中商品數量同下
//添加商品數量block
cell.addGoodNumBlock = ^(ShopingCartTableViewCell *cell)
{
NSIndexPath *indexPath = [self.tableViewindexPathForCell:cell];
NSDictionary *goodsDic = [self.dataSourceobjectAtIndex:indexPath.section];
NSArray *goodsArray = [goodsDic objectForKey:@"array"];
self.good = [goodsArrayobjectAtIndex:indexPath.row];
self.good.num = [cell.numTF.textintValue]+1;
// 增加商品數量
if ([selfalertNum])
{
cell.numTF.text = [NSStringstringWithFormat:@"%d",[cell.numTF.textintValue] + 1];
}
// 修改總金額
if (cell.checkboxBtn.selected)
{
[self alertSelecedGoodNum];
// 計算價格
[self alertSum];
indexPath = [NSIndexPath indexPathForRow:0 inSection:self.dataSource.count];
NSArray *indexArray=[NSArrayarrayWithObject:indexPath];
[self.tableViewreloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];
}
};