菜鸟教程小白 发表于 2022-12-11 20:55:16

iOS:包装在导航 Controller 中时将数据传递给模态 VC


                                            <p><p>我有一个以模态方式呈现的 VC,但是该 VC 封装在 <code>UINavigationController</code> 中。为了展示连接到我的 VC 的导航 Controller ,我在 Storyboard 中添加了一个标识符,如下所示:</p>

<pre><code>if let nvc = self.storyboard?.instantiateViewController(withIdentifier: &#34;EditTaskNavController&#34;) {
   self.present(nvc, animated: true){
      success(true)
   }         
}
</code></pre>

<p>这很好。
当我尝试将数据传递给我的 VC 时,问题就出现了。因为 nvc 是导航 Controller ,所以我尝试使用 <code>nvc.rootViewController</code> 获取 vc,但出现错误:<code>Value of type 'UIViewController' has no member 'rootViewController'</code>。如果我打印出 <code>nvc</code>,我发现它实际上是一个 <code>UINavigationController</code>。我认为发生此错误是因为我使用 <code>instantiateViewController</code> 从 Storyboard 中获取导航 Controller ,但我很困惑为什么它打印为 <code>UINavigationController</code>。</p>

<p>我也尝试将 <code>nvc 转换为? TaskEditViewController</code> 但 nvc 是导航 Controller 而不是 vc 所以这不起作用。</p>

<p>最终我想在模态呈现之前将数据传递给我的 VC:
<code>vc.detail = "示例"</code></p>

<p>任何想法如何做到这一点?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>您需要将 <code>instantiateViewController</code> 的结果转换为适当的类型,作为您在 Storyboard 中设置标识符的 vc 类型,因为它返回类型为 <code>UIViewController</code> 的通用对象,所以将其转换为 <code>UINavigationController</code> ,同样的情况也适用于需要转换的属性 <code>topViewController</code> </p>

<pre><code>if let nvc = self.storyboard?.instantiateViewController(withIdentifier: &#34;EditTaskNavController&#34;) as? UINavigationController, let top = nvc.topViewController as? TaskEditViewController {
    top.someProperty = /* some value */

    self.present(nvc, animated: true) {
      /* some code */
    }
}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于iOS:包装在导航 Controller 中时将数据传递给模态 VC,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/53584415/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/53584415/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: iOS:包装在导航 Controller 中时将数据传递给模态 VC