【问题标题】:Move screen transition of ViewController class from another class从另一个类移动 ViewController 类的屏幕转换
【发布时间】:2018-01-16 06:35:37
【问题描述】:

我的问题与标题完全相同。

请参阅下面的代码。
每个代码都列在一个单独的文件中。

我在 ViewController 类中写了一个屏幕转换的方法(作为 func goToSecondView ())。
然后我们决定在另一个文件(FirstFile)中的“iconATapped”方法中创建一个实例,并进行 ViewController 的屏幕转换。

但是,它没有成功并发出以下错误。

let next = storyboard!.instantiateViewController(withIdentifier: "secondView")
//Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value


此错误在调用 Action 方法时有效。

请告诉我解决这个问题的方法。

//FirstFile

import UIKit

class goNextPage: UIView {

    @IBAction func iconATapped(_ sender: Any) {
        ViewController.goToSecondView()
    }

}


//SecondFile

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func goToSecondView(){
        let next = storyboard!.instantiateViewController(withIdentifier: "secondView")
        self.present(next,animated: true, completion: nil)
    }
}

【问题讨论】:

  • 你到底想做什么?
  • 你为什么把goToSecondView放在另一个视图控制器中?把它放在第一个文件有什么问题?
  • 要么你的 storyboard 变量为零,要么你的故事板中没有名为 secondView 的标识符。
  • 添加您的代码以初始化情节提要变量。

标签: ios swift xcode swift4 xcode9


【解决方案1】:

您正在使用 ViewController.goToSecondView() 并且在 goToSecondView 中您正在使用 self

self.present(next,animated: true, completion: nil)

这里你的 self 将是 nil,因为你没有使用 ViewController 的变量,而是它的类名。所以没有 ViewController 的实例,因此导致 nil。

尝试在您的第一个文件中创建 ViewController 的变量,然后尝试呈现新的 Vc。希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-04
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多