通过点击按钮,把当前页面的textFiled的值传递给所跳转页面的textFiled显示
ViewControl。m
#import "ViewController.h"
#import "SecondViewController.h"
@interface ViewController ()
{
UITextField*textFieldsender;
NSString *str;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//设置view的背景颜色
[self.view setBackgroundColor:[UIColor grayColor]];
//创建一个Button按钮
UIButton*btn=[[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
[btn setBackgroundColor:[UIColor orangeColor]];
[btn setTitle:@"传值" forState:UIControlStateNormal];
//点击按钮 跳转到另一个页面
[btn addTarget:self action:@selector(pushToSecond:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
//创建一个textFiled
textFieldsender=[[UITextField alloc]initWithFrame:CGRectMake(100, 300, 100, 30)];
[textFieldsender setBackgroundColor:[UIColor yellowColor]];
// textFieldsender.placeholder=@"Hello";
//在上面定义的全局的字符串 赋值给textfiled的text属性
textFieldsender.text=str;
[self.view addSubview:textFieldsender];
}
//自定义一个方法,用来传值
/* //如果需要跳转的那个页面 返回过来一个值 再启用这个方法
- (instancetype)initWithName:(NSString *)name
{
self = [super init];
if (self) {
str=[NSString stringWithString:name];
NSLog(@"%@",str);
}
return self;
}
*/
//跳转页面的方法
-(void)pushToSecond:(UIButton*)sender{
SecondViewController*secondVC=[[SecondViewController alloc]initWithName:textFieldsender.text];
[self.navigationController pushViewController:secondVC animated:YES];
}
SecondViewController.m
#import "SecondViewController.h"
#import "ViewController.h"
@interface SecondViewController ()
{
NSString *str;
UITextField *lab;
}
@end
@implementation SecondViewController
- (instancetype)initWithName:(NSString *)name
{
self = [super init];
if (self) {
str=[NSString stringWithString:name];
NSLog(@"%@",str);
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
UIButton*btn=[[UIButton alloc]initWithFrame:CGRectMake(100, 400, 100, 100)];
[btn setBackgroundColor:[UIColor orangeColor]];
[btn setTitle:@"传值" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(pushToSecond:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
[self.view setBackgroundColor:[UIColor grayColor]];
label=[[UITextField alloc]initWithFrame:CGRectMake(100, 100, 300, 100)];
[label setBackgroundColor:[UIColor brownColor]];
label.text=str;
[self.view addSubview:label];
}
-(void)pushToSecond:(UIButton*)sender{
ViewController *vc=[[ViewController alloc]init];
//如果要把当前页面的值传回去,启用这个方法
// ViewController *vc=[[ViewController alloc]initWithName:label.text];
[self.navigationController pushViewController:vc animated:YES];
}