iOSBlock回调

214 阅读1分钟

在第二个页面的.h中

#import <UIKit/UIKit.h>
//块语法回传第一步,声明
typedef void(^ShowTextBlock)(NSString *text);
@interface NextViewController : UIViewController
//快语法回传第二步,声明块类型的对象
@property(nonatomic,copy) ShowTextBlock showTextBlock;
@end

在第二个页面的.m中

#import "NextViewController.h"

@interface NextViewController ()

@end

@implementation NextViewController
- (IBAction)clickReturn:(UITextField *)sender {
//块语法回传第三步,适当的位置调用
    _showTextBlock(sender.text);
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor orangeColor];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

在第一个页面的.h中获取:

#import "MyViewController.h"
#import "NextViewController.h"
@interface MyViewController ()
@property (weak, nonatomic) IBOutlet UILabel *label;
@end
@implementation MyViewController
- (IBAction)click:(id)sender {
    NextViewController *nextVC = [NextViewController new];
//第四步:获取到回调信息.
    nextVC.showTextBlock = ^(NSString *text){
        _label.text = text;
    };
    [self presentViewController:nextVC animated:YES completion:nil];
}
- (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.
}