Block的基本运用, 适用于初学
ViewController.m
#import "ViewController.h"
#import "secondViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *tf;
@end
@implementation ViewController
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
NSLog(@"视图将要出现");
}
- (IBAction)present:(UIButton *)sender {
secondViewController *svc = [[secondViewController alloc]init];
[svc setBlock:^(NSString *text) {
if (text.length >0) {
self.tf.text = text;
}
return _tf.text;
}];
[self presentViewController:svc animated:YES completion:^{
NSLog(@"你是一只小小狗,你是个骨头");
}];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
secondViewController.h
#import <UIKit/UIKit.h>
typedef NSString *(^TextBlock)(NSString *);
@interface secondViewController : UIViewController
@property (nonatomic,copy)TextBlock block;
- (void)setBlock:(TextBlock)block;
@end
secondViewController.m
#import "secondViewController.h"
@interface secondViewController ()
@property (weak, nonatomic) IBOutlet UITextField *tf;
@end
@implementation secondViewController
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
_tf.text=_block(NULL);
}
- (IBAction)dismiss:(UIButton *)sender {
_block(_tf.text);
[self dismissViewControllerAnimated:YES completion:^{
NSLog(@"只有我才能带领你们走向胜利");
}];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
屏幕快照 2016-03-11 下午8.13.17.png
屏幕快照 2016-03-11 下午8.13.28.png