【问题标题】:Swift 4: Class coming up as nil and crashing after pushing navigation controllerSwift 4:推送导航控制器后类出现为零并崩溃
【发布时间】:2018-08-22 09:45:20
【问题描述】:

我正在尝试使用 pushViewController 实现从一个 ViewController 到下一个 ViewController 的转换。我想在我的 CollectionView 中的一个单元格被点击时执行此操作。点击单元格后,我希望将 CollectionView 中填写的信息显示在以下 ViewController 上。

我相信我在正确的轨道上执行此操作,但是当 ViewController 被推送时,我尝试将信息分配给一个标签,我遇到了崩溃。

DidSelectRowAtIndexPath

//这是我调用函数来推送导航控制器的适当信息

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    var fellow = whoWeAreOptions[indexPath.row]
    handleFullBio(fellow: fellow)
}

//这是我用类信息推送ViewController的函数

func handlePush(fellow: WhoWeAreOption) {
    let fellowController = UIViewController()

//Here is the view that is assigned to the bounds of my new ViewController
    let bioView = FullBioView(frame: UIScreen.main.bounds)

//I declare the view's fellow here which should stop the class from being nil
    bioView.fellow = fellow

    fellowController.navigationItem.title = "Full Biography"
    fellowController.view.backgroundColor = .white
    fellowController.view.addSubview(bioView)
    navigationController?.pushViewController(fellowController, animated: true)
}

FullBioView

//这是分配给ViewControllers边界的视图

class FullBioView: UIView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

//Here is my class which should have been assigned in the previous function
var fellow: WhoWeAreOption!

let nameLabel: UILabel = {
    let text = UILabel()
    text.text = "Username"
    text.font =  UIFont(name: "Avenir Next", size: 24.0)
    text.font = UIFont.boldSystemFont(ofSize: 22.0)
    text.translatesAutoresizingMaskIntoConstraints = false
    text.textColor = Color.blue

    return text
}()

override init(frame: CGRect) {
    super.init(frame: frame)              

//I try to assign my class information to a label and the program crashes
    nameLabel.text = fellow.name
}

我已经玩了几天了,但仍然没有得出任何可靠的结果。这是解决这个问题的适当方式吗?当我在 handlePush 函数中分配类时,我不明白为什么我的类显示为 nil。

提前致谢。

【问题讨论】:

  • 尽量不要强制解包,而不是 var fellow: WhoWeAreOption! 使用 var fellow: WhoWeAreOption? 。除非你能保证它们的价值,否则最好不要强制使用选项。
  • bioView.fellow = fellow 在哪里初始化这个家伙? :'D
  • 感谢您的回复。不幸的是,当应用可选时没有出现。
  • Rakesha 考虑到它需要形成 CollectionView 单元格,我假设这个家伙已经初始化,这是正确的吗?
  • 嗯...我不知道。您会知道,因为您会在代码中的某处对其进行初始化?绝对不在你分享的代码中。

标签: ios swift xcode


【解决方案1】:

这是崩溃的原因:

fellowController.view.backgroundColor = .white
fellowController.view.addSubview(bioView)

nilfellowController.view。在 viewController 的视图加载完成之前,您无法访问它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多