iOS block用法

來源:互聯網
上載者:User

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];

}

};



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.