您的位置:首页 > 移动开发 > IOS开发

ios开发 Block(二) 实现委托

2014-11-06 17:34 253 查看
委托和block是IOS上实现回调的两种机制。Block基本可以代替委托的功能,而且实现起来比较简洁,比较推荐能用block的地方不要用委托。

实现效果如图



第一步,自定义CustomCell

#import <Foundation/Foundation.h>

@interface CustomCell : UITableViewCell

@property (strong, nonatomic) IBOutlet UILabel *labName;
@property (copy,nonatomic) void(^BuyGoods)(NSString *);

- (IBAction)ButtonBuyPressed:(id)sender;

@end


#import "CustomCell.h"

@implementation CustomCell

- (IBAction)ButtonBuyPressed:(id)sender {

NSString *goodName=_labName.text;
_BuyGoods(goodName);

}

@end




在custom.h文件里面有

@property (copy,nonatomic) void(^BuyGoods)(NSString *);

声明了一个block变量

在custom.m文件里面回调

NSString *goodName=_labName.text;

_BuyGoods(goodName);

下面看实现的类里面

#import "ViewController.h"
#import "CustomCell.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

_tabGoods.delegate=self;
_tabGoods.dataSource=self;
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CustomCell";
CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.labName.text = [NSString stringWithFormat:@"商品名称%d",indexPath.row];
__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];
};

return cell;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 10;
}

@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代码块里面使用.........

运行效果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐