【发布时间】:2017-02-22 06:25:23
【问题描述】:
我正在使用 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)
}
}
//SecondVC
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。
【问题讨论】:
-
不要使用对象传递数据,这样不行。看看下面的答案。
标签: ios swift uiviewcontroller nsnotificationcenter