简体   繁体   English

滚动视图:在展开可选值时意外发现nil

[英]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.

相关问题 标头自定义视图:在展开可选值时意外发现nil - Header Custom View: unexpectedly found nil while unwrapping an Optional value 展开Optional值时意外发现nil - unexpectedly found nil while unwrapping an Optional value 展开可选的value()时意外找到nil - Unexpectedly found nil while unwrapping an Optional value() 值不是nil,但是在展开Optional值时意外发现nil - value is not nil but getting unexpectedly found nil while unwrapping an Optional value 打开UIViewController时解开Optional值时意外发现nil - Unexpectedly found nil while unwrapping an Optional value while opening UIViewController 展开可选值时意外发现nil,但是有一些值 - unexpectedly found nil while unwrapping optional value, but there is some value 使用panGestureRecognizer滑出视图时出现“在找到可选值时意外发现nil” - Getting “unexpectedly found nil while unwrapping an Optional value” while using panGestureRecognizer for slide out view 迅捷的Xcode:解开可选值(lldb)时意外发现nil - swift Xcode: unexpectedly found nil while unwrapping an Optional value (lldb) ARQuicklook-致命错误:展开一个可选值时意外发现nil - ARQuicklook - Fatal error: Unexpectedly found nil while unwrapping an Optional value 展开可选值WKWebView get参数时意外发现nil - unexpectedly found nil while unwrapping an Optional value WKWebView get parameters
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM