Block传值原理
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Block传值原理相关的知识,希望对你有一定的参考价值。
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
@interface ViewController : UIViewController<UITextFieldDelegate>
@property (nonatomic ,strong) UITextField *textName;
@property (nonatomic ,strong) UIButton *button;
@end
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"5622630220130817130527093.jpg"]];
self.textName = [[UITextField alloc ] initWithFrame:CGRectMake(100, 100, 100, 50)];
self.textName.backgroundColor = [UIColor grayColor];
self.textName.textColor = [UIColor greenColor];
self.textName.delegate = self;
[self.view addSubview:self.textName];
self.button = [[UIButton alloc] initWithFrame:CGRectMake(120, 160, 80, 40)];
[self.button setTitle:@"下一页" forState:UIControlStateNormal];
[self.button addTarget:self action:@selector(nextPage) forControlEvents: UIControlEventTouchUpInside ];
[self.view addSubview:self.button];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
if ([self.textName isFirstResponder]) {
[self.textName resignFirstResponder];
}
return YES;
}
-(void)nextPage
{
SecondViewController *second = [[SecondViewController alloc] init];
second.str = self.textName.text;
second.postvalueb = ^(NSString *str){
self.textName.text = str;
NSLog(@"%@",str);
};
[self presentViewController:second animated:YES completion:^{
NSLog(@"页面跳转成功");
}];
}
#import <UIKit/UIKit.h>
typedef void(^postValueBlock)(NSString *);
@interface SecondViewController : UIViewController<UITextFieldDelegate>
@property (nonatomic ,strong) NSString *str;
@property (nonatomic ,strong) postValueBlock postvalueb;
@property (nonatomic ,strong) UITextField *textFil;
@end
@implementation SecondViewController
- (void)viewDidLoad {
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"5622630220130817130527093.jpg"]];
self.textFil = [[UITextField alloc ] initWithFrame:CGRectMake(100, 100, 100, 50)];
self.textFil.backgroundColor = [UIColor grayColor];
self.textFil.textColor = [UIColor greenColor];
//属性传值
self.textFil.text = self.str;
self.textFil.delegate = self;
[self.view addSubview:self.textFil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
if(self.postvalueb){
self.postvalueb(self.textFil.text);
}
if ([self.textFil isFirstResponder]) {
[self.textFil resignFirstResponder];
}
[self dismissViewControllerAnimated:YES completion:nil];
return YES;
}
@end
以上是关于Block传值原理的主要内容,如果未能解决你的问题,请参考以下文章