[英]Scroll View: unexpectedly found nil while unwrapping an Optional value
I'm trying to make call a method from another class when a button is pressed, but it is not working and giving a fatal error (unexpectedly found nil while unwrapping an Optional value). 我试图在按下按钮时从另一个类中调用方法,但是它无法正常工作并给出致命错误(在展开Optional值时意外发现nil)。 I don't know if I'm doing something wrong. 我不知道我做错了什么。
Here's the code from the first class (FirstViewController) 这是来自第一类(FirstViewController)的代码
@IBAction func pressButton(sender: UIButton) {
SecondViewController().pressedButton()
}
Here's the code in another class (SecondViewController) 这是另一个类(SecondViewController)中的代码
func pressedButton() {
self.scrollView.setContentOffset(CGPoint(x: 320, y: 0), animated: true)
}
I placed the above code right after viewDidLoad
(Within SecondViewController's class). 我将上面的代码放在viewDidLoad
之后(在SecondViewController的类中)。
The problem is that in your first code SecondViewController()
creates a whole new SecondViewController instance. 问题在于,在您的第一个代码中, SecondViewController()
创建了一个全新的SecondViewController实例。 That is not the same SecondViewController that has a scrollView
, so its scrollView
is nil and you crash when you try to use it. 那与具有scrollView
,因此其scrollView
为nil,当您尝试使用它时会崩溃。
Instead, a SecondViewController needs to exist already in your view controller hierarchy, and you need to talk to that SecondViewController. 相反,在视图控制器层次结构中必须已经存在SecondViewController,并且需要与该 SecondViewController进行对话。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.