在兩個(gè)頁面之間傳送數(shù)據(jù),可以使用通知機(jī)制實(shí)現(xiàn).
例如, 點(diǎn)擊頁面A的按鈕, 數(shù)據(jù)由頁面A -- > 頁面B , 操作步驟:
- 定義頁面A按鈕的點(diǎn)擊事件:
@IBAction func save(_ sender: Any) {
self.dismiss(animated: true) { () -> Void in
let dataDict = ["username" : "123"]
//采用通知機(jī)制將dataDict傳給頁面B
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "RegisterCompletionNotification"), object: nil, userInfo: dataDict)
}
}
- 在頁面B注冊(cè)通知和回調(diào)方法:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//注冊(cè)通知 RegisterCompletionNotification
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.register(_:)), name: NSNotification.Name(rawValue: "RegisterCompletionNotification"), object: nil)
}
//定義回調(diào)方法
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)
}
}