【问题标题】:Swift open new UIViewControllerSwift 打开新的 UIViewController
【发布时间】:2017-04-02 22:52:01
【问题描述】:

当我点击UICollectionView 中的一个项目时,我试图打开新的UIViewController,但使用此代码我的应用程序崩溃,Xcode 和模拟器重新启动,所以我什至看不出问题出在哪里。

import UIKit

class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.register(CustomCell.self, forCellWithReuseIdentifier: "cellId")
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! CustomCell

        cell.imageViewGame.image = UIImage(named: imageArray[indexPath.row])

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width / 2, height: view.frame.width / 2)
    }

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        performSegue(withIdentifier: "postController", sender: title[indexPath.row])
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "postController" {
            let postController = segue.destination as! PostController

            postController.title = sender as! String

        }
    }
}

有人从这段代码中知道我的应用为什么会崩溃吗?如果它很重要,我不会使用情节提要。

【问题讨论】:

  • 您还必须写下您收到的错误消息。我们不是预兆。
  • 1.调试日志说什么? 2. postController 标识符是否存在?
  • 我看不到错误信息,我的 Xcode 每次都崩溃。
  • PostController 存在,和 ViewController 差不多。
  • 如果 Xcode 崩溃,这是 Xcode 中的一个错误,应该向 Apple 报告。但是你的问题是说你的应用程序崩溃了,在这种情况下会有一个崩溃日志。请张贴那个象征性的崩溃日志。

标签: ios uiviewcontroller swift3


【解决方案1】:

试试这个:

  1. 让您不要忘记在您的 segue 中声明 postController 标识符

  1. 您可以通过以下方式以模态方式呈现它:

覆盖 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let postController = PostController()
        postController.title = title[indexPath.row]
        present(postController, animated: true, completion: nil)
    }

【讨论】:

  • 我根本没有使用故事板。过去我在故事板方面遇到了一些问题,所以我决定按照一些专业人士的建议放弃它。现在我想弄清楚如何在没有情节提要的情况下做到这一点。
  • 如果你使用故事板,你的 segue 的定义在哪里?
  • 我没有。我认为这不是必需的,它仅用于准备函数,因此它可以确定它应该执行哪个序列。
  • @user3593157 你如何识别一个最初没有被识别的segue?如果您想以编程方式显示 UIViewController,请不要使用 segue,而是使用 presentViewController 或 pushViewController 方法。搜索SO有很多例子。
  • 谢谢,我想它成功了,虽然现在我完全黑屏,而 PostController 里面有东西,它不是黑的。
猜你喜欢
  • 1970-01-01
  • 2018-11-25
  • 1970-01-01
  • 2012-06-13
  • 2021-03-03
  • 2018-01-01
  • 1970-01-01
  • 2013-01-09
  • 2015-09-04
相关资源
最近更新 更多