【问题标题】:How to receive information from View Controller which is embed in Navigation Controller如何从嵌入在导航控制器中的视图控制器接收信息
【发布时间】:2019-09-13 10:29:04
【问题描述】:

我有两个视图控制器“ViewController”和“ChildViewController”。如果单击 HomeButton,它们之间的连接会通过 segue 发生。 segue 标识符是“parentToChild”。如果单击 ChildButton,则使用委托方法将信息转到“ViewController”。如果“ChildViewController”没有嵌入到导航控制器中,所有这些都有效。 如果它是嵌入的,那​​么我在展开委托 (delegate!.buttonClickedByUser(word: "hello")) 时会出错,并且错误是“在展开可选值时意外发现 nil”

我的代码如下所示:

import UIKit

class ViewController: UIViewController, ChildToParentProtocol
{
    func buttonClickedByUser(word: String) {
        print(word)
    } 

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let vc = segue.destination as? ChildViewController,
            segue.identifier == "parentToChild" {
            vc.delegate = self
        }
    }
}
import UIKit

protocol ChildToParentProtocol:class {
    func buttonClickedByUser(word: String)
}


class ChildViewController: UIViewController {
    weak var delegate:ChildToParentProtocol!

    override func viewDidLoad() {
        super.viewDidLoad()

    }
    @IBAction func childButtonClicked(_ sender: UIButton) {
        delegate!.buttonClickedByUser(word: "hello")
    }

}

即使 ChildViewController 嵌入到导航控制器中,我也希望打印“hello”

【问题讨论】:

  • if let vc = segue.destination as? ChildViewController, 返回 false,对吗?然后,做if let navVC = segue.destination as? UINavigationController, let childVC = navVC. viewControllers.first as? ChildViewController {}

标签: ios swift


【解决方案1】:

如果它嵌入到 NavigationController 中,这行代码将失败:

if let vc = segue.destination as? ChildViewController

目的地不会是ChildViewController,而是UINavigationController,其根视图控制器是ChildViewController

如果它在导航控制器中,这样的东西应该可以工作:

if let nav = segue.destination as? UINavigationController, 
    let vc = nav.viewControllers.first as? ChildViewController {
    vc.delegate = self
}

【讨论】:

    猜你喜欢
    • 2017-10-24
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    • 2018-11-09
    • 2019-06-01
    • 1970-01-01
    相关资源
    最近更新 更多