目的:
A页面push到B页面,点击B页面的按钮传值到A页面,分别用delegate和Block来实现
1.在页面B定义delegate和Block
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| importUIKit
@objcprotocolDetailedViewControllerDelegate {
@objcoptionalfuncchangeValue (value:Int) ->Void;
}
classDetailedViewController:UIViewController{ var_title:String? vardelegate:DetailedViewControllerDelegate? varcount:Int=0 varchangeBlock:((Int) -> ())? overridefuncviewDidLoad() { super.viewDidLoad() navigationItem.title=_title self.view.backgroundColor=UIColor.brown weakvarweakSelf =self letbtn =CGButton.shendInstance().createButton(frame:CGRect(), bgColor:UIColor.red, title:"按钮", superView:self.view) { (action)in weakSelf?.count+=1 letcout = weakSelf?.count // Block回调 if(weakSelf?.changeBlock! !=nil) { weakSelf?.changeBlock!(cout!) } // 代理回调 if((weakSelf?.delegate?.changeValue) !=nil) { weakSelf?.delegate?.changeValue!(value: cout!) } } } funcchangeValue(value:@escaping(Int) -> ()) ->Void{ self.changeBlock= value }
}
|
2.在push的时候
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| moiveView.clickdidSelectItemAt{ (collection, indexPath)in letdataModel =self._movieView.dataSource[indexPath.item]as!MovieModel letDetailedVC =DetailedViewController() DetailedVC.delegate=self //Block的回调 DetailedVC.changeValue(value: { (value)in print("blockChange\(value)") }) DetailedVC._title= dataModel.titleasString self.navigationController!.pushViewController(DetailedVC, animated:true) }
// delegate的回调 funcchangeValue(value:Int) { print("delegateChange\(value)") }
|