Search code examples
swiftxcodeautolayout

Subview Has Size Miscalculated on Storyboard


I have the below issue:

enter image description here

This happens on certain screen sizes only. This view is in a nib linked to a separate file listed here:

import Foundation
import UIKit

class FooterActionView : UIView {

    @IBOutlet weak var actionButton: UIButton!

    let nibName = "FooterActionView"

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

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

    func commonInit() {
        guard let view = loadViewFromNib() else { return }
        view.frame = self.bounds
        self.addSubview(view)
    }

    func loadViewFromNib() -> UIView? {
        let nib = UINib(nibName: nibName, bundle: nil)
        return nib.instantiate(withOwner: self, options: nil).first as? UIView
    }

}

I have confirmed that the constraints on the storyboard are completely correct (and wouldn't result in this miscalculation of the view width). This view is subclassed from another view controller as follows:

Where can I look to see what's causing this? (Again I'm fairly certain it's not the constraints). I tried googling this but couldn't find anything that seemed to explain it. Any help is greatly appreciated.

enter image description here


Solution

  • You are saying

        view.frame = self.bounds
    

    at a time when we do not yet know what self.bounds is. Then the constraints kick in and the bounds of self.bounds change. But the frame of view.frame doesn’t.

    A simple solution would be to give your view the ability to resize itself when self.bounds changes:

        view.frame = self.bounds
        view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    

    Or you could wait until layoutSubviews to set view.frame.