跟通知一样也是两个控制器,然后代码创建控件直接上代码
#import "ViewController.h"
#import "TwoViewController.h"
@interface ViewController ()
{
UIButton *_nextBtn;
UILabel *_showLabel;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self show];
}
-(void)show{
_nextBtn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
[_nextBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[_nextBtn setTitle:@"下一个" forState:UIControlStateNormal];
[_nextBtn addTarget:self action:@selector(nextBtnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_nextBtn];
_showLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 300, 100,50)];
[_showLabel setBackgroundColor:[UIColor greenColor]];
[_showLabel setTextColor:[UIColor redColor]];
[self.view addSubview:_showLabel];
}
-(void)nextBtnClick:(UIButton *)nextBtnClick{
TwoViewController * two = [[TwoViewController alloc]init];
two.block = ^(NSString * str){
_showLabel.text = str;
};
[self presentViewController:two animated:YES completion:nil];
}
在TwoViewController.h中
#import <UIKit/UIKit.h>
typedef void (^MyBlock)(NSString *);
@interface TwoViewController : UIViewController
@property(nonatomic,copy)MyBlock block;
@end
在TwoViewController.m中
#import "TwoViewController.h"
@interface TwoViewController ()
{
UIButton *_backBtn;
UITextField *_textField;
}
@end
@implementation TwoViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor blueColor];
[self shoulabel];
}
-(void)shoulabel{
_backBtn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
_backBtn.backgroundColor = [UIColor redColor];
[_backBtn setTitle:@"shang" forState:UIControlStateNormal];
[_backBtn addTarget:self action:@selector(shangBtnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_backBtn];
_textField = [[UITextField alloc]initWithFrame:CGRectMake(100, 400, 250, 35)];
_textField.backgroundColor = [UIColor yellowColor];
[self.view addSubview: _textField];
}
-(void)shangBtnClick:(UIButton *)shangBtn{
[self dismissViewControllerAnimated:YES completion:^{
if (self.block) {
self.block(_textField.text);
}
}];
}
这样就进行了简单的传值