How to separate view from viewcontroller using storyboard swift?

401 Views Asked by At

Practicing MVC pattern and want to separate view from viewcontroller using storyboard.

in main.storyboard I have a viewcontroller, and there are some uilabels in rootview.

to separate view code from viewcontroller, I selected view from viewcontroller scene , created FruitDetailView class and subclassed it in storyboard identity inspector.

enter image description here

enter image description here

And connected UILabels to FruitDetailView class.

class FruitDetailView: UIView {

    @IBOutlet weak var name: UILabel!
    @IBOutlet weak var type: UILabel!

    override init(frame: CGRect) {
        super.init(frame: frame)
        name.text = ""
        type.text = ""
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func update(_ detail: Fruit) {
        name.text = detail.name
        type.text = detail.type
    }
    
}

In the viewController , created FruitDetailView() instance. And in loadview() methods, assigned fruitDetailView instance to view property.

class FruitDetailViewController: UIViewController {
    
    private let fruitDetailView = FruitDetailViewController()
    var fruit = Fruit()
    
    override func loadView() {
        view = fruitDetailView
        fruitDetailView.update(fruit)
    }

}

But when I run the app, app crashes with error.

enter image description here

How can I fix this?

1

There are 1 best solutions below

0
DrainOpener On

Your problem is you want to reach your FruitDetail class created before even its properties being created. Put a breakpoint to the name.text = "" and run and you will see what i mean. To solve this just control your nil value safely :

if let label = name { // by the way consider in future to assign values like nameLabel rather than name
    name.text = "put your string value"
}