Swift - 无法从子视图控制器调用公共函数? ViewController没有成员错误?

时间:2016-07-20 17:12:12

标签: ios swift

好吧,所以在过去我能够像这样创建新的子视图控制器,然后能够轻松调用其中的函数:

.one {
  background-color: green;
  color: white;
  height: 40px;
}
.two {
  background-color: red;
  color: white;
  height: 40px;
  display: in-line;
}
.main div:hover + .two,
.main div p:first-child:hover + .two {
  display: none;
}

其中doSomething是Results VC类中的公共函数,其中任何对象都是发送者。

我正在尝试做同样的事情,同时创建VC略有不同但我收到错误enter image description here

有了这个:

在班级我有<div class="main"> <div class="one"> <p>Hover to hide div below</p> </div> <div class="two"> <p>hide me please</p> </div> </div> <div class="main"> <div class="one"> <p>Hover to hide div below (this works)</p> <div class="two"> <p>hide me please</p> </div> </div> </div>

然后在一个函数中:

let v : ResultsViewController = ResultsViewController (nibName: "ResultsViewController", bundle: nil)
self.addChildViewController(v)
        self.view.addSubview(v.view)
        v.didMoveToParentViewController(self)

        v.view.frame = self.view.bounds

v.doSomething(self)

结果2课程中我总是喜欢

var skip = UIViewController()

我必须以这种方式编写它,而不仅仅是将{跳转到skip = Results2ViewController (nibName: "Results2ViewController", bundle: nil) self.addChildViewController(skip) self.view.addSubview(skip.view) skip.didMoveToParentViewController(self) skip.view.frame = self.view.bounds self.view.bringSubviewToFront(skip.view) //make sure accept is there self.view.bringSubviewToFront(circleView) skip.definesPresentationContext = false; skip.view.frame.origin.x -= self.view.bounds.width skip.setIdeaLabels(self) //ERROR ,因为我在其他地方重用了这个跳过变量,变量将超出范围。

为什么我不能在子视图控制器中调用函数?为什么没有会员?

1 个答案:

答案 0 :(得分:1)

当您声明var skip = UIViewController()时,skip会被隐式输入为UIViewController。在声明变量后,您无法更改变量的类型 - Results2ViewControllerUIViewController,因此它“适合”skip。但编译器仍将其视为UIViewController,因此它没有Results2ViewController的方法。

您可以将实例变量设置为具有正确的类型,您可以在需要调用该方法时将其强制转换,也可以使用正确类型的本地引用来调用该方法。

1)将var skip = UIViewController()替换为var skip : Results2ViewController?请注意我如何skip可选,并且未将其初始化为任何内容。你也可以使用var skip = Results2ViewController (nibName: "Results2ViewController", bundle: nil),但我认为你有一些理由不首先这样做。

2)在致电skip之前投出setIdeaLabels

skip = Results2ViewController (nibName: "Results2ViewController", bundle: nil)
var results = skip as! Results2ViewController;
results.setIdeaLabels(self);

3)在本地初始化,然后在完成后将其设置为skip

let results = Results2ViewController (nibName: "Results2ViewController", bundle: nil)
results.setIdeaLabels(self);
skip = results;

选项2和3非常相似。我纯粹是因为我不喜欢使用额外的演员。我喜欢1,但它让你有很多可能在整个地方打开一个可选项。

相关问题