ios开发 Block(二) 实现委托
委托和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)viewDidLoad 11 { 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)didReceiveMemoryWarning 20 { 21 [super didReceiveMemoryWarning]; 22 // Dispose of any resources that can be recreated. 23 } 24 25 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 26 { 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代码块里面使用.........
运行效果图:
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。