先创建两个UIViewController(系统自带算一个)
从SecondView向ViewController传值:
#import "ViewController.h"
#import "SecondViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIButton *button =[UIButton buttonWithType:UIButtonTypeContactAdd];
button.frame =CGRectMake(100, 100, 30, 30);
[button addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
UILabel *label =[[UILabel alloc]initWithFrame:CGRectMake(20, 200, 300, 100)];
label.backgroundColor=[UIColor grayColor];
label.font=[UIFont systemFontOfSize:25];
label.tag=100;
label.textAlignment=NSTextAlignmentCenter;
[self.view addSubview:label];
//接受通知
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receive:) name:@"tongzhi" object:nil];
}
-(void)receive:(NSNotification *)noti
{
//需要把通知的信息给取出来
NSString *str =noti.userInfo[@"str"];
UILabel *label =(UILabel *)[self.view viewWithTag:100];
label.text=str;
}
-(void)btnClicked
{
SecondViewController *secVC = [[SecondViewController alloc]init];
[self presentViewController:secVC animated:YES completion:nil];
}
#import "SecondViewController.h"
@interface SecondViewController ()<UITextFieldDelegate>
@end
@implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor=[UIColor whiteColor];
UITextField *textFiled =[[UITextField alloc]initWithFrame:CGRectMake(20, 200, 300, 100)];
textFiled.backgroundColor=[UIColor orangeColor];
textFiled.placeholder=@"this is textFiled!";
[textFiled becomeFirstResponder];
textFiled.delegate=self;
[self.view addSubview:textFiled];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
[self dismissViewControllerAnimated:YES completion:nil];
/**
* 通知传值,,邮件等。。。。
*/
//创建通知
NSNotification *noti =[[NSNotification alloc]initWithName:@"tongzhi" object:self userInfo:@{@"str":textField.text}];
//发送通知
[[NSNotificationCenter defaultCenter]postNotification:noti];
return YES;
}
好了,就这么多,主要代码已经在其中用不同的颜色标记。