1.OC中
声明Block
.h文件中
@interface notNetWorkView : UIView
@property (nonatomic, copy) void(^notNetWorkBlock)();
@end
.m文件中
UIButton *noNetBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 39)];
[noNetBtn addTarget:self action:@selector(noNetBtnClick:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:noNetBtn];
- (void)noNetBtnClick:(UIButton *)send {
if (self.notNetWorkBlock) {
self.notNetWorkBlock();
}
}
在需要使用的页面调用
self.netWorkNotConnectView.notNetWorkBlock = ^(){
JWNetworkNotConnectVC *CompletePersonData = [[UIStoryboard storyboardWithName:@"NetWorkConnect" bundle:nil] instantiateViewControllerWithIdentifier:@"NetworkNotConnect"];
[weakSelf.navigationController pushViewController:CompletePersonData animated:YES];
};
2.Swift中
import UIKit
typealias btnBlock = (Int) -> () //声明
class RolodexNav1: UIView {
var btnBlock:btnBlock? //初始化
@IBAction private func btnClick(_ sender: UIButton) {
//tag: 1 排序 2 pop
if self.btnBlock != nil {
btnBlock!(sender.tag) //调用
}
}
}
3.案例一
block回调
UMengShareManage调用testFunction
UMengShareManage.testFunction(title,desc,shareBack: {(err:Error?) -> () in
//用err参数toDoSomething
})
testFunction回调block的实现细节
定义一个block类型,
typealias ShareBack = (Error?) -> ()
设置一个ShareBack类型block全局变量
static var shareBackBlock:ShareBack?
在数据处理完后用block把数据传出来
UMengShareManage.share(plattype: plattype, messageObject: messageObject, viewController: VC) { (data:Any?, error:Error?) in
if shareBackBlock != nil {
self.shareBackBlock!(error)
}
}
在testFunction中执行全局block把数据放在shareBack block参数中传回去
UMengShareManage. testFunction(title:String?,desc:String?,shareBack:@escaping ShareBack){
self.shareBackBlock = {(err:Error?) -> () in
shareBack(err)
}
})
4.案例二
swift中闭包回调把数据传过来
网友评论