標籤:style blog http io color ar os 使用 for
委託和block是IOS上實現回調的兩種機制。Block基本可以代替委託的功能,而且實現起來比較簡潔,比較推薦能用block的地方不要用委託。
實現效果
第一步,自訂CustomCell
1 #import <Foundation/Foundation.h> 2 3 @interface CustomCell : UITableViewCell 4 5 @property (strong, nonatomic) IBOutlet UILabel *labName; 6 @property (copy,nonatomic) void(^BuyGoods)(NSString *); 7 8 - (IBAction)ButtonBuyPressed:(id)sender; 9 10 @end
1 #import "CustomCell.h" 2 3 @implementation CustomCell 4 5 6 7 - (IBAction)ButtonBuyPressed:(id)sender { 8 9 NSString *goodName=_labName.text;10 _BuyGoods(goodName);11 12 }13 14 @end
在custom.h檔案裡面有
@property (copy,nonatomic) void(^BuyGoods)(NSString *);
聲明了一個block變數
在custom.m檔案裡面回調
NSString *goodName=_labName.text;
_BuyGoods(goodName);
下面看實現的類裡面
1 #import "ViewController.h" 2 #import "CustomCell.h" 3 4 @interface ViewController () 5 6 @end 7 8 @implementation ViewController 9 10 - (void)viewDidLoad11 {12 [super viewDidLoad];13 // Do any additional setup after loading the view, typically from a nib.14 15 _tabGoods.delegate=self;16 _tabGoods.dataSource=self;17 }18 19 - (void)didReceiveMemoryWarning20 {21 [super didReceiveMemoryWarning];22 // Dispose of any resources that can be recreated.23 }24 25 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath26 {27 static NSString *CellIdentifier = @"CustomCell";28 CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];29 if (cell == nil) {30 NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];31 cell = [nib objectAtIndex:0];32 }33 cell.labName.text = [NSString stringWithFormat:@"商品名稱%d",indexPath.row];34 __block NSString *tipMsg=cell.labName.text;35 cell.BuyGoods=^(NSString *str){36 UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示內容" message:tipMsg delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];37 [alertView show];38 };39 40 return cell;41 }42 43 -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{44 return 1;45 }46 47 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{48 return 10;49 }50 51 @end
在ViewController.m檔案裡面
__block NSString *tipMsg=cell.labName.text;
cell.BuyGoods=^(NSString *str){
UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"提示內容" message:tipMsg delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
[alertView show];
};
實現Block裡面的代碼塊,__block NSString *tipMsg=cell.labName.text;這一行保證變數能在block代碼塊裡面使用.........
運行:
ios開發 Block(二) 實現委託