Swift反向传值

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
    }

Demo地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值