Terrance Terrance - 7 months ago 33
Swift Question

Visual constraints not being recognized

I simply want to set constraints which allows the

UIWebView
to fill the screen. (Screen has a
UINavigationbar
and a
UIToolBar
), I've tried following the examples given in the apple documentation but always get a warning and my view doesnt show up. Below is what I've tried.

private func addSubviews(){
navigationController?.setToolbarHidden(false, animated: false)
// webView = UIWebView(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height))

webView = UIWebView(frame: CGRectZero)
webView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(webView)
let views = ["myView" : webView]
let formatString = "|-[myView]-|"
let constraints = NSLayoutConstraint.constraintsWithVisualFormat(formatString, options:[] , metrics: nil, views: views)

NSLayoutConstraint.activateConstraints(constraints)
}

Answer

Oofh, visual constraints make my head hurt. I never was a fan of the visual language, never made any sense to me. This may be a bit more code but I think it's much easier to read as a developer and far more expressive as to intent.

self.view.addSubview(webView)
self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: .Left, relatedBy: .Equal, toItem: webView, attribute: .Left, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: .Top, relatedBy: .Equal, toItem: webView, attribute: .Top, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: .Bottom, relatedBy: .Equal, toItem: webView, attribute: .Bottom, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: self.view, attribute: .Right, relatedBy: .Equal, toItem: webView, attribute: .Right, multiplier: 1, constant: 0))

These constraints pin all edges of a view to the respective edge with a distance of 0.

Then at the end of your constraints, don't forget:

self.view.layoutIfNeeded()

My problem with the visual language is I can't look at it and immediately be clear as to what it does. Here, it's quite explicit.