在两个页面之间传送数据,可以使用通知机制实现.
例如, 点击页面A的按钮, 数据由页面A -- > 页面B , 操作步骤:
- 定义页面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)
}
}
- 在页面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)
}
}