【问题标题】:How to execute a function from second ViewController after popViewController?如何在 popViewController 之后从第二个 ViewController 执行功能?
【发布时间】:2020-11-12 13:32:41
【问题描述】:

我是一名 Android 开发人员,试图将我的应用程序移植到 iOS 上,这是我第一次使用 Swift 和 Xcode 或任何一般的 Mac。该应用程序用于扫描二维码,如果二维码无效,我希望它返回上一个屏幕并显示敬酒。我已经制作了一个显示二维码无效的吐司的功能。

func found(code: String) {
    print(code)
    // convert JSON to object
    do {
        let qrMessage = try JSONDecoder().decode(QrMessage.self, from: code.data(using: .utf8)!)
        print("QrMessage object - device name: " + qrMessage.pcName)
        
    }
    catch let error {
        print(error)
        _ = navigationController?.popViewController(animated: true)
        // call ShowInvalidQrToast() from the new VC that is now on top of the ViewController stack
    }

编辑: 我设法从该线程的第一个答案中找到了使用 NotificationCenter 的解决方案:Calling function from another ViewController in swift。更多信息在我下面的答案中。如果您认为有更好的方法,请发布您自己的答案。

【问题讨论】:

  • 如果问题解决了,请删除问题或回答问题以将其关闭。

标签: ios swift uiviewcontroller uinavigationcontroller uistoryboard


【解决方案1】:

我使用NotificationCenter的解决方案:

在 ConnectViewController 中

override func viewDidLoad() {
    super.viewDidLoad()
    ...
    NotificationCenter.default.addObserver(self, selector: #selector(showInvalidQrCodeToast(_:)), name: Notification.Name(rawValue: "showInvalidQrCodeToast"), object: nil)

}

@objc func showInvalidQrCodeToast(_ notification: Notification) {
    self.view.makeToast("Invalid QR code")
}

在 ScannerViewController 中

func found(code: String) {
    print(code)
    // convert JSON to object
    do {
        let qrMessage = try JSONDecoder().decode(QrMessage.self, from: code.data(using: .utf8)!)
        print("QrMessage object - device name: " + qrMessage.pcName)
        
    }
    catch let error {
        print(error)
        _ = navigationController?.popViewController(animated: true)
        NotificationCenter.default.post(name: Notification.Name(rawValue: "showInvalidQrCodeToast"), object: nil)

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多