2
votes

I have created an xib file with a UIView inside of it. I am using this view inside of my storyboard, and would like it to resize based on the content within it. When I explicitly set the height of the view in the storyboard, it is the same height as the XIB file. Each phone screen seems to have the same xib height and width as well, which causes the view to go off the screen, no matter what I set the constraints to be within the storyboard.

I have tried this to hide the view and set the height of the banner to 35

self.specialistBanner.pillView.isHidden = true  
specialistBannerHeight.constant = 35

I have tried

specialistBannerHeight.constant = 35

to get the view to be smaller within the storyboard

I have also tried

self.specialistBanner.sizeToFit()

with no avail

XIB File for the specialist banner view XIB File for the specialist banner view

Label inside the xib file Label inside the xib file

Pill View within the xib Pill View within the xib

Storyboard file using the xib view inside of a view controller Storyboard file using the xib view inside of a view controller

class SpecialistBannerView: UIView {

@IBOutlet weak var bannerTitle: UILabel!
@IBOutlet weak var pillView: PillCollectionView!

var viewModel = SpecialistBannerViewModel()

// Initialize xib
let SpecialistBannerView = "SpecialistBannerView"

override func awakeFromNib() {
    super.awakeFromNib()
    self.translatesAutoresizingMaskIntoConstraints = false
}

override init(frame: CGRect) {
    super.init(frame: frame)
    initXib(view: self)
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    initXib(view: self)
}

func initXib(view: SpecialistBannerView) {

    let viewToShow = Bundle.main.loadNibNamed(SpecialistBannerView, owner: self, options: nil)?[0] as? UIView ?? UIView()
    view.translatesAutoresizingMaskIntoConstraints = false
    view.sizeToFit()
    view.addSubview(viewToShow)
    view.frame = view.bounds
    view.pillView.setUp()
    view.sizeToFit()

    view.autoresizingMask = [.flexibleHeight, .flexibleWidth]

    viewModel.specialistBannerViewProtocol = self
}

Any help would be appreciated

1

1 Answers

9
votes

I had your same problem. I found the answer in another question. You have to override LayoutSubViews() in your custom view and set the bounds

override func layoutSubviews() {
    super.layoutSubviews()

    // we need to adjust the frame of the subview to no longer match the size used
    // in the XIB file BUT the actual frame we got assinged from the superview
    self.view.frame = self.bounds
}