【问题标题】:How do I pass an object into a view via presentViewController?如何通过 presentViewController 将对象传递到视图中?
【发布时间】:2016-09-13 05:31:22
【问题描述】:

如何将数据传递到我以编程方式呈现但已在 IB 中创建的视图控制器中?现在我有代码可以在用户单击按钮时拉出视图,但不清楚如何将数据发送到该视图中。

我正在尝试使用下面的代码,但被告知“UIViewController 类型的值没有成员“数据””

@IBAction func showPossButton(sender: UIButton) {

    print("Show data table.")


    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewControllerWithIdentifier("PossTable")
    var data:Data!
    vc.data = data

    self.presentViewController(vc, animated: true, completion: nil)

}

我在这里做错了什么?

【问题讨论】:

  • let vc = storyboard.instantiateViewControllerWithIdentifier("PossTable") as! PossibleViewController(或该场景的任何基类)。
  • 这似乎奏效了。你能解释一下我为什么不知道这样做或那在做什么而缺少的概念吗?是不是我需要同时指向 IB 中的场景和 xCode 的视图控制器才能将我的数据对象与正确的东西相关联?而且我只是指向场景而不是视图控制器本身,我试图在其中获取数据!对象?
  • 概念如下:instantiateViewControllerWithIdentifier方法被定义为返回一个UIViewController。编译器无法知道您碰巧在 Interface Builder 中定义的 UIViewController 子类,因此您必须告诉它。所以,是的,你必须告诉 IB 在实例化场景时使用什么基类,你还必须告诉编译器将此变量转换为什么。
  • 好的。我认为我需要更好地理解一般的“铸造”,因为这些 UIViewControllers 都只是变量,尽管是花哨的变量,但对我来说还不直观。

标签: ios swift presentviewcontroller


【解决方案1】:

就像 Rob 提到的那样,您必须将实例化的视图控制器转换为具有 data 字段和 as! *insertViewControllerClassName* 的特定类

【讨论】:

    【解决方案2】:

    UIStoryboard.instantiateViewControllerWithIdentifier() 返回UIViewController 对象。您必须将此对象强制转换为您的 ViewController。

    你的方法应该是这样的:

    @IBAction func showPossButton(sender: UIButton) {
        print("Show data table.")
    
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        if let vc = storyboard.instantiateViewControllerWithIdentifier("PossTable") as? PossTableViewController {
            var data: Data! = self.selectedData // Data from your parent VC
            vc.data = data
            self.presentViewController(vc, animated: true, completion: nil)
        }
        else {
            print("Can't cast view controller to PossTableViewController")
        }
    }
    

    【讨论】:

      【解决方案3】:

      就像 Rob 在 cmets 中所说的:

      let vc = storyboard.instantiateViewControllerWithIdentifier("PossTabl‌​e") as! PossibleViewController(或该场景的任何基类)

      为什么?

      这是由于一种叫做多态性的东西。这基本上意味着您可以像这样创建变量:

      let vc: UIViewController = SomeOtherViewController()
      

      虽然我们都知道vc 存储了一个SomeOtherViewController 实例,但编译器只知道它是UIViewController 类型。因此,我们无法访问SomeOtherViewControllervc 的成员。

      instantiateViewControllerWithIdentifier 基本上是一回事。它返回一个UIViewController 类型的值。这会导致编译器不知道它实际上是一个PossibleViewController。这就是它找不到data 属性的原因。

      所以要让编译器知道,您需要将返回值转换为您想要的类型,因为知道它必须包含PossibleViewController 的实例。

      【讨论】:

        猜你喜欢
        • 2017-08-05
        • 2018-07-05
        • 2016-11-04
        • 1970-01-01
        • 2018-10-29
        • 2015-05-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多