我在两个视图之间的通知/观察者仅在我来回后才有效

时间:2019-02-22 18:42:18

标签: ios swift nsnotificationcenter

如标题所述,我想更改第二个视图中的标签文本。但是从第一个按钮单击起它不起作用,我需要反复更改它,有人可以在这方面为我提供帮助吗?

这是我的第一个初始视图控制器,其中包含第二个的旅行按钮

import UIKit

let vc1 = ViewController()
class ViewController2: UIViewController {
    @IBAction func QickModeButton(_ sender: Any) {
        self.dismiss(animated: true, completion: nil)
        let name = Notification.Name(rawValue: quickgameNotificationKey)
        NotificationCenter.default.post(name: name , object: nil)
    }

    @IBAction func chooseButton(_ sender: Any) {
        let name = Notification.Name(rawValue: bestof3NotificationKey)
        NotificationCenter.default.post(name: name , object: nil)
        self.dismiss(animated: true, completion: nil)


    }

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    }

这是标签所在的第二个

import UIKit


extension UIColor {
    static var random: UIColor {
        return UIColor(red: .random(in: 0...1),
                       green: .random(in: 0...1),
                       blue: .random(in: 0...1),
                       alpha: 1.0)
    }
}

let bestof3NotificationKey = "co.Drake.bestof3"
let quickgameNotificationKey = "co.Drake.quick"

class ViewController: UIViewController {

    let bestof3 = Notification.Name(rawValue: bestof3NotificationKey)
    let quick = Notification.Name(rawValue: quickgameNotificationKey)

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    @IBOutlet var CommunicationLabel: UILabel!
    @IBOutlet var playAgainoutlet: UIButton!




    override func viewDidLoad() {
        super.viewDidLoad()

            self.createobservers()


            winningLabel.isHidden = true
            winningLabel.center = CGPoint(x: winningLabel.center.x, y: winningLabel.center.y - 400)
      playAgainoutlet.isHidden = true
            playAgainoutlet.center = CGPoint(x: playAgainoutlet.center.x, y: playAgainoutlet.center.y + 400)
    }





    func createobservers(){
        // quick mode button observer
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.updateLabel(notification:)), name: quick, object: nil)

        // bestof3 mode button observer
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.updateLabel(notification:)), name: bestof3, object: nil)

    }



    @objc func updateLabel(notification:NSNotification){


            let isbestof3 = notification.name == self.bestof3 // this here is setting up a variable if notification.name == bestof3 (isbestof3 will then be equal to true)
            let labeltext = isbestof3 ? "Best of 3" : "quick"
            self.CommunicationLabel.text = labeltext



    }


}

感谢您的帮助,谢谢!

1 个答案:

答案 0 :(得分:1)

第二个ViewController的{​​{1}}

viewDidLoad
尚未调用

,因为尚未显示。在显示视图之前,没有观察者。 (override func viewDidLoad() { super.viewDidLoad() self.createobservers()