iOS Block逆向传值

2018-02-27 11:10:56来源:https://www.jianshu.com/p/d24edf95f568作者:泼泼泼人点击

分享



逆向传值的方法有很多如代理、通知、block、KVC等等。但是相对来说block是最简单方便的,前提是处理好使用block的细节问题,如循环引用这常见的问题。


一.注意点
传值方定义block,接收方只需告诉传值方我们需要你传值了。
传值方定义block,接收方实现block。
在需要传值的时候调用block。
接收方在需要用到传值的地方告诉传值方,你可以传值了,接收值并处理逻辑。
二.实现效果


逆向传值
三.实现步骤
1.接收方
#define HPWidth self.view.frame.size.width
#define HPHeight self.view.frame.size.height
#import "ViewController.h"
#import "HPReverseViewController.h"
@interface ViewController ()
@property (nonatomic ,strong) UILabel *label;
@property (nonatomic ,strong) UIButton *btn;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"block逆向传值";
self.view.backgroundColor = [UIColor whiteColor];
[self btn];
[self label];


}
- (void)buttonClick{
HPReverseViewController *reverseVc = [[HPReverseViewController alloc]init];
__weak typeof(self) weakSelf = self;
reverseVc.reverseValueBlock = ^(NSString *HPReverseValue) {
weakSelf.label.text = HPReverseValue;
};
[self.navigationController pushViewController:reverseVc animated:YES];
}
- (UIButton *)btn{
if (!_btn) {
_btn = [UIButton buttonWithType:UIButtonTypeCustom];
_btn.frame = CGRectMake(HPWidth/2-40,150,80, 50);
_btn.titleLabel.font = [UIFont systemFontOfSize:18];
[_btn setTitle:@"下一步" forState:UIControlStateNormal];
[_btn setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
[_btn addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_btn];
}
return _btn;
}
- (UILabel *)label{
if (!_label) {
_label = [[UILabel alloc]init];
_label.frame = CGRectMake(HPWidth/2-50, 300, 100, 50);
_label.backgroundColor = [UIColor greenColor];
_label.textAlignment = NSTextAlignmentCenter;
_label.font = [UIFont systemFontOfSize:18];
_label.text = @"逆向传值";
[self.view addSubview:_label];
}
return _label;
}

@end

2.传值方
.h文件
#import <UIKit/UIKit.h>
/**
定义一个block类型

@param HPReverseValue 逆向传值
*/
typedef void (^HPReverseValueBlock) (NSString *HPReverseValue);

@interface HPReverseViewController : UIViewController
/**
声明block属性 在接收方实现.
*/
@property (nonatomic ,copy) HPReverseValueBlock reverseValueBlock;
@property (weak, nonatomic) IBOutlet UIButton *backBtn;
@property (weak, nonatomic) IBOutlet UITextField *valueTextFile;
@end
-------------------------------------------------------------------------------
.m文件
#import "HPReverseViewController.h"
@interface HPReverseViewController ()
@end
@implementation HPReverseViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"传值方";
}
- (IBAction)btnClick:(id)sender {
__weak typeof(self) weakSelf = self;
if (self.reverseValueBlock) {
//将值传到接收方
weakSelf.reverseValueBlock(weakSelf.valueTextFile.text);
}

[self.navigationController popViewControllerAnimated:YES];


}

@end








最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台