swift 通知传值

场景:A页面跳转到B页面,B页面返回到A页面,(B页面给A页面传值)

B页面逻辑:发送通知

A页面逻辑:创建通知,移除通知

B页面代码:

  @IBAction func back(_sender:UIButton) {

          let  dic = ["name":passTf.text??""]

        //多值传递

        NotificationCenter.default.post(name:NSNotification.Name(rawValue:"value"), object:nil, userInfo: dic)

        //单值传递

        NotificationCenter.default.post(name:NSNotification.Name(rawValue:"passValue"), object:"zyy",userInfo:nil)

        self.navigationController?.popViewController(animated:true)

    }

A页面代码: 

override func viewDidLoad() {

        super.viewDidLoad()

        self.view.backgroundColor = UIColor.white

        self.title="第一页"

        NotificationCenter.default.addObserver(self, selector:#selector(change(info:)), name:NSNotification.Name(rawValue:"value"), object:nil)

         NotificationCenter.default.addObserver(self, selector:#selector(change1(info:)), name:NSNotification.Name(rawValue:"passValue"), object:nil)

    }

   @objc  func change(info:NSNotification)  {

    print(info.userInfo) // 类型为[AnyHashable,Any]

    let dic = info.userInfo as! Dictionary

    textLabel.text = dic[AnyHashable("name")] as! String

    }


    @objc  func change1(info:NSNotification)  {

        print(info.object)

    }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容