看一下效果图:
//
// ViewController.h
// Block
//
// Created by LiuMingchuan on 15/9/29.
// Copyright © 2015年 LMC. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
- (IBAction)btnToSecond:(id)sender;
@property (strong, nonatomic) IBOutlet UILabel *infoLabel;
@end
//
// ViewController.m
// Block
//
// Created by LiuMingchuan on 15/9/29.
// Copyright © 2015年 LMC. All rights reserved.
//
#import "ViewController.h"
#import "SecondViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.infoLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.infoLabel.numberOfLines = 0;
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)btnToSecond:(id)sender {
UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
SecondViewController *sec = [storyBoard instantiateViewControllerWithIdentifier:@"second"];
SetInfoBlock setInfoBlock = ^(NSString *info){//创建SetInfoBlock类型的block
self.infoLabel.text = info;//block体的作用就是将传入block的文字列赋值给我们第一个视图的UILabel的text属性
};
//设定secondViewController的block
[sec setInfo:setInfoBlock];
[sec setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
[self presentViewController:sec animated:YES completion:nil];
}
@end
//
// SecondViewController.h
// Block
//
// Created by LiuMingchuan on 15/9/30.
// Copyright © 2015年 LMC. All rights reserved.
//
#import <UIKit/UIKit.h>
/**
* Block的定义
*
* @param info 文字列形参
*/
typedef void(^SetInfoBlock)(NSString *info);
@interface SecondViewController : UIViewController
- (IBAction)backToOneBtn:(id)sender;
@property (strong, nonatomic) IBOutlet UITextView *inputText;
/**
* 自定义block的声明
*/
@property (nonatomic,copy) SetInfoBlock setInfoBlock;
/**
* 用来设定本Controller的block
*
* @param setInfoBlock <#setInfoBlock description#>
*/
- (void)setInfo:(SetInfoBlock)setInfoBlock;
@end
//
// SecondViewController.m
// Block
//
// Created by LiuMingchuan on 15/9/30.
// Copyright © 2015年 LMC. All rights reserved.
//
#import "SecondViewController.h"
#import "ViewController.h"
@implementation SecondViewController
- (IBAction)backToOneBtn:(id)sender {
//当我们的block不为nil时进行处理
if (self.setInfoBlock != nil) {
//将我们输入的内容传入从第一个视图传进来的block中
self.setInfoBlock(self.inputText.text);
}
[self dismissViewControllerAnimated:YES completion:nil];
}
/**
* 接受外部传入的block
*
* @param setInfoBlock 传入的block
*/
- (void)setInfo:(SetInfoBlock)setInfoBlock{
self.setInfoBlock = setInfoBlock;
}
@end