我正在使用 Swift 3 开发一个测试项目。我正在尝试使用 NotificationCenter 将 textField 字符串从一个类传递到另一个类。我正在尝试从此链接中找出答案:pass NSString variable to other class with NSNotification和 how to pass multiple values with a notification in swift
我从上面的链接中尝试了几个答案,但没有任何效果。
我的代码:
//第一个VC
import UIKit
extension Notification.Name {
public static let myNotificationKey = Notification.Name(rawValue: "myNotificationKey")
}
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func sendData(_ sender: AnyObject) {
let userInfo = [ "text" : textView.text ]
NotificationCenter.default.post(name: .myNotificationKey, object: nil, userInfo: userInfo)
}
}
//第二VC
import Foundation
import UIKit
class viewTwo: UIViewController {
@IBOutlet weak var result: UILabel!
override func viewDidLoad() {
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(self.notificationReceived(_:)), name: .myNotificationKey, object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self, name: .myNotificationKey, object: nil)
}
func notificationReceived(_ notification: Notification) {
guard let text = notification.userInfo?["text"] as? String else { return }
print ("text: \(text)")
result.text = text
}
我不确定代码有什么问题。上面,我从第一个链接找到的最初标记为已回答的代码。代码已转换为 Swift。
最佳答案
不要使用对象参数来传递数据。它旨在过滤具有相同名称但来自特定对象的通知。因此,如果您在发布通知时传递了一些对象,而在添加观察者时传递了另一个对象,您将不会收到它。如果你传递 nil,你基本上关闭了这个过滤器。
您应该改用 userInfo
参数。
首先,最好将通知的名称定义为Notification.Name 的扩展名。这种方法更安全,更易读:
extension Notification.Name {
public static let myNotificationKey = Notification.Name(rawValue: "myNotificationKey")
}
发布通知:
let userInfo = [ "text" : text ]
NotificationCenter.default.post(name: .myNotificationKey, object: nil, userInfo: userInfo)
订阅:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(self.notificationReceived(_:)), name: .myNotificationKey, object: nil)
}
取消订阅:
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self, name: .myNotificationKey, object: nil)
}
要调用的方法:
func notificationReceived(_ notification: Notification) {
guard let text = notification.userInfo?["text"] as? String else { return }
print ("text: \(text)")
}
关于ios - NotificationCenter 在 Swift 中传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40015748/