标签:
//声明一个文本框和一个按钮
@property(strong,nonatomic)UITextField *textName;
@property(strong,nonatomic)UIButton *button;
ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.textName=[[UITextField alloc] initWithFrame:CGRectMake(100, 100, 150, 40)];
self.textName.borderStyle=1;
self.button=[[UIButton alloc] initWithFrame:CGRectMake(100, 200, 100, 40)];
self.button.backgroundColor=[UIColor redColor];
[self.button setTitle:@"按钮" forState:UIControlStateNormal];
[self.button addTarget:self action:@selector(nextPage) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.textName];
[self.view addSubview:self.button];
//指定代理
// self.textName.delegate=self;
}
-(void)nextPage
{
secondViewController *second=[[secondViewController alloc] init];
second.str=self.textName.text;
//代理
// second.delegate=self;
second.myblock=^(NSString *str)
{
self.textName.text=str;
};
[self presentViewController:second animated:YES completion:^{
NSLog(@"转到下一页");
}];
}
//协议方法的实现
-(void)postValue:(NSString *)value
{
self.textName.text=value;
}
secondViewController.h
typedef void(^ValueBlock)(NSString *str);
//代理传值中的协议
@protocol postValueDelegate <NSObject>
-(void)postValue:(NSString *)value;
@end
//遵循协议
@interface secondViewController : UIViewController<UITextFieldDelegate>
@property(strong,nonatomic)NSString *str;
@property(strong,nonatomic)UITextField *txt2;
@property(strong,nonatomic)UIButton *button2;
//用协议定义的一个属性
@property(strong,nonatomic)id<postValueDelegate> delegate;
//代码块定义的一个属性
@property(strong,nonatomic)ValueBlock myblock;
secondViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor=[UIColor grayColor];
self.txt2=[[UITextField alloc] initWithFrame:CGRectMake(100, 100, 150, 40)];
self.txt2.borderStyle=1;
[self.view addSubview:self.txt2];
// self.button2=[[UIButton alloc] initWithFrame:CGRectMake(100, 200, 100, 40)];
// [self.button2 setTitle:@"返回" forState:UIControlStateNormal];
// [self.button2 addTarget:self action:@selector(backPage) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.button2];
//属性传值
self.txt2.text=self.str;
NSLog(@"str=%@",self.str);
self.txt2.delegate=self;
}
//-(void)backPage
//{
// //代理传值
// if (self.delegate)
// {
// [self.delegate postValue:self.txt2.text];
// }
//
//
// [self dismissViewControllerAnimated:YES completion:^{
// NSLog(@"返回");
// }];
//}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
//代码块传值
if (self.myblock)
{
self.myblock(textField.text);
}
if ([textField isFirstResponder])
{
[textField resignFirstResponder];
}
[self dismissViewControllerAnimated:YES completion:^{
NSLog(@"返回");
}];
return YES;
}
标签:
原文地址:http://www.cnblogs.com/layios/p/5281616.html