1.Block
B页面定义Block
typealias passByValueBlock = (String) ->()
var pbvBlock :passByValueBlock?
func getPassByValueBlock(block :passByValueBlock?){
pbvBlock = block
}
//按钮点击事件
@objc func btnAction(){
if let block = self.pbvBlock{
block("block传参")
}
self.navigationController?.popViewController(animated: true)
}
A页面
let detail = BlockNotiDelegateDetailVC()
detail.getPassByValueBlock { (value) in
self.label.text = value
}
self.navigationController?.pushViewController(detail, animated: true)
2. delegate
B页面
protocol passByValueDelegate {
func didDeleteText(text:String)
}
var delegate : passByValueDelegate?
//按钮点击事件
@objc func btn1Action(){
delegate?.didDeleteText(text: "delegate传值")
self.navigationController?.popViewController(animated: true)
}
A页面
遵循passByValueDelegate代理
let detail = BlockNotiDelegateDetailVC()
detail.delegate = self
self.navigationController?.pushViewController(detail, animated: true)
/*passByValueDelegate*/
func didDeleteText(text: String) {
print("delegate===",text)
delgateLB.text = text
}
3通知
B页面
let NotiName = NSNotification.Name(rawValue: "MYNOTI")
//按钮点击事件
@objc func btn2Action(){
NotificationCenter.default.post(name: NotiName, object: "通知传值")
self.navigationController?.popViewController(animated: true)
}
A页面
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
//接收通知
let noti = NSNotification.Name(rawValue: "MYNOTI")
NotificationCenter.default.addObserver(self, selector: #selector(getNoti(notif:)), name: noti, object: nil)
}
//通知
@objc func getNoti(notif:NSNotification){
guard let text : String = notif.object as! String? else{ return }
self.notiLB.text = text
}