使用通知机制在不同页面传送数据

在两个页面之间传送数据,可以使用通知机制实现.

例如, 点击页面A的按钮, 数据由页面A -- > 页面B , 操作步骤:

  1. 定义页面A按钮的点击事件:
 @IBAction func save(_ sender: Any) {     
        self.dismiss(animated: true) { () -> Void in
            let dataDict = ["username" : "123"]
            //采用通知机制将dataDict传给页面B
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "RegisterCompletionNotification"), object: nil, userInfo: dataDict)
        }
    }
  1. 在页面B注册通知和回调方法:
import UIKit
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        //注册通知 RegisterCompletionNotification
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.register(_:)), name: NSNotification.Name(rawValue: "RegisterCompletionNotification"), object: nil)
    }

    //定义回调方法
    func register(_ notification:Notification) {
        let theData = notification.userInfo!
        let username = theData["username"] as! String
        NSLog("username = %@", username)
    }

    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        NotificationCenter.default.removeObserver(self)
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容