您的位置:首页 > 其它

Controller之间传递数据:属性传值

2015-07-06 15:51 459 查看
在项目中,Controller之间传递数据非常之多,这里简单介绍一下属性传值。例如有FirstController 和 SecondController,数据从First传递到Second中,我们如何操作呢,比如我们传递一个字符串到Second,那么我们就可以在Second中创建一个属性,在First中,推向Second的时候,为Second中那个属性赋值即可。

代码如下所示:

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
32
33
34
35

/////////////////FirstViewController//////////////////
- (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];

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(130, 170, 60, 40);
[button setTitle:@"传值" forState:UIControlStateNormal];
[button addTarget:self action:@selector(sendValue:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}

- (void)sendValue:(id)sender
{
//获取textfd里面的数据
UITextField *textfield = (UITextField *)[self.view viewWithTag:100];
//初始化第二个second
SecondViewController *second = [[SecondViewController alloc]init];
//为second中的name属性赋值
second.name = textfield.text;
//推过去
[self.navigationController pushViewController:second animated:YES];
[second release];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}

Objective-C

1
2
3
4
5
6
7
8
9
10
11
12
13

////////////////////SecondViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UILabel *nameLable = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 300, 60)];
nameLable.textAlignment = UITextAlignmentCenter;
nameLable.font = [UIFont systemFontOfSize:50];
nameLable.textColor = [UIColor blueColor];
//将属性的值赋值给这个label
nameLable.text = self.name;
[self.view addSubview:nameLable];
[nameLable release];
}

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