iOS块传值
块传值,块类似于C中的函数指针。在Controller中传递数据非常方便,还是继续上一章的例子,将数据从Second传递到First,这里使用块来完成,看起来似乎和协议很像,不过比协议略简单。
代码如下所示:
///////////
////////FirstViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.nameLable = [[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 300, 60)]autorelease];
self.nameLable.textAlignment = UITextAlignmentCenter;
self.nameLable.font = [UIFont systemFontOfSize:50];
self.nameLable.textColor = [UIColor blueColor];
[self.view addSubview:self.nameLable];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(130, 170, 60, 40);
[button setTitle:@"下一个" forState:UIControlStateNormal];
[button addTarget:self action:@selector(pushNext:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)pushNext:(id)sender
{
//初始化second
SecondViewController *second = [[SecondViewController alloc]init];
///调用块
second.send = ^(NSString *str){
self.nameLable.text = str;
};
//推过去
[self.navigationController pushViewController:second animated:YES];
[second release];
}
Objective-C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/////////////
////////////SecondViewController.h
#import <UIKit/UIKit.h>
typedef void (^SendMessage) (NSString *str); ///声明块
@inte易做图ce SecondViewController : UIViewController<UITextFieldDelegate>
@property (nonatomic, copy) SendMessage send; //声明一个块类型属性
@end
/////////SecondViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
UITextField *textFd = [[UITextField alloc]initWithFrame:CGRectMake(10, 10, 300, 150)];
textFd.borderStyle = UITextBorderStyleRoundedRect;
textFd.delegate = self;
textFd.tag = 100;
[self.view addSubview:textFd];
[textFd release];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
//先判断,在调用块传递实参
if (self.send) {
self.send (textField.text);
}
return YES;
}
补充:移动开发 , IOS ,