Swift 4:在推送导航控制器后,类变为nil并崩溃

时间:2018-08-21 18:40:48

标签: ios swift xcode

我正在尝试使用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。

谢谢。

1 个答案:

答案 0 :(得分:0)

这是崩溃的原因:

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

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