Search code examples
swiftxcodestoryboardxib

UIView created from XIB file is not showing


I have created a xib file in my project which looks like this

enter image description here

I'm initializing it with this code

class MainItem: UIView {
    class func instanceFromNib() -> UIView {
        let view = UINib(nibName: "MainItem", bundle: nil).instantiate(withOwner: nil, options: nil).first as! UIView
        return view
    }
}

stackView.addArrangedSubview(MainItem.instanceFromNib())

and I'm adding it to a UIStackView which already has some views like UILabel or UIScrollView. but the added view is not showing when I'm running the app and here is the result enter image description here enter image description here

what is the problem?


Solution

  • One possible reason is that you did not specify the height of the view, so the height of it becomes to 0 during the rendering process. There are two ways to do it:

    1. Set the alignment of you stackView to .fillEqually. You can do this because the label has non 0 intrinsic heigh.

      stackView.distribution = .fillEqually

    2. Tell iOS how to calculate the height of your view. For example override intrinsicContentSize of your view