Jacob Parker Jacob Parker - 1 year ago 73
iOS Question

Layout Constraints are not working

I have a UIButton added in the storyboard with the bottom, left, and right set to the superview’s; and the height set to a hard-coded 60: it’s the width of the superview, and placed at the bottom.

I’m trying to add another view to the superview to give a total of two views. I want this view to fill the remainder of the space. I’m trying this code,

override func viewDidLoad() {
// Do any additional setup after loading the view, typically from a nib.
locationManager = LocationManager()

webview = WKWebView()
webview.backgroundColor = .blue
webview.translatesAutoresizingMaskIntoConstraints = true
webview.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleTopMargin, .flexibleBottomMargin]

var constraints: [NSLayoutConstraint] = ([.top, .width] as [NSLayoutAttribute]).map {
NSLayoutConstraint(item: webview, attribute: $0, relatedBy: .equal, toItem: view, attribute: $0, multiplier: 1, constant: 0)
constraints.append(NSLayoutConstraint(item: webview, attribute: .bottom, relatedBy: .equal, toItem: connectionButton, attribute: .top, multiplier: 1, constant: 0))


However, the effect is that the button takes up the entirety of the screen, and I can’t see the new view at all. What am I doing wrong?

Answer Source

You're close, but missing a couple of key things:

  1. When creating your own constraints, you don't want to use the auto resizing mask constraints, so set webview.translatesAutoresizingMaskIntoConstraints to false and you don't need the autoresizingMask line.

  2. You set the width equal to the view, but didn't define any x position. You can also constrain the leading edges or the horizontal centers to define the position.

I think that will fix your issues.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download