在Swift中同时用代理和Block(Closure)回调
目的:
A页面push到B页面,点击B页面的按钮传值到A页面,分别用delegate和Block来实现
1.在页面B定义delegate和Block
```
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!)
}
}
btn.snp.makeConstraints{ (make)in
make.top.equalTo(0)
make.left.equalTo(100)
make.width.height.equalTo(100)
}
}
funcchangeValue(value:@escaping(Int) -> ()) ->Void{
self.changeBlock= value
}
}
```
2.在push的时候
```
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)")
}
```