Search code examples
iosswiftautolayout

Does a view need to be init with a frame and then have auto-layout change it or just use auto-layout?


I have a custom view that I have implemented and I am trying to learn how to use auto-layout without the use of the storyboard.

My question is do I need to init my view with a frame, or can I just do an empty init and then use auto layout to have the view figure out the width and height by itself?

Below you will see that I have tried adding the frame and then putting the auto-layout thinking that I have to put a frame first and then auto-layout changes it.

let origin = CGPoint(x: 0.0, y: 0.0)
let size = CGSize(width: view.frame.width, height: 44.0)

let frame = CGRect(origin: origin, size: size)

customView = ExpandableHeadingView(frame: headingFrame)

customView.frame.size.height = 44.0

view.addSubview(customView)

view.topAnchor.constraint(equalTo: customView.topAnchor).isActive = true
view.leftAnchor.constraint(equalTo: customView.leftAnchor).isActive = true
view.rightAnchor.constraint(equalTo: customView.rightAnchor).isActive = true
view.heightAnchor.constraint(equalTo: customView.heightAnchor).isActive = true

Solution

  • You shouldn't set the frame. You just need to set enough constraints for autolayout to be able to set it for you.

    One thing you're missing that may be a problem is:

    customView.translatesAutoresizingMaskIntoConstraints = false
    

    If you're creating a view in code, you generally need to set this manually to be able to properly use it with autolayout.