2016-11-08 AutoLayout in a playground

Last edit

Summary: What got me confused today, was how to play with AutoLayout in a Playground. The trick is to first create a main view, akin to the view in a View . . .

Changed:

< [[autolayout_in_Xcode_2016-11-08.png]]

to

> [[image:autolayout_in_Xcode_2016-11-08.png]]


What got me confused today, was how to play with AutoLayout in a Playground. The trick is to first create a main view, akin to the view in a View Controller, that is sized with a frame (without constraints).

After that's set up, add subviews that use AutoLayout. The following works for Xcode 8.1:

    import UIKit
    let view = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
    view.backgroundColor = UIColor.white
    view.layer.borderWidth = 2.0
    let licensePlateView = UIView()
    licensePlateView.translatesAutoresizingMaskIntoConstraints = false
    licensePlateView.backgroundColor = UIColor.gray
    view.addSubview(licensePlateView)
    licensePlateView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
    licensePlateView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    licensePlateView.widthAnchor.constraint(equalToConstant: 200).isActive = true
    licensePlateView.heightAnchor.constraint(equalToConstant: 50).isActive = true
    view.layoutIfNeeded()
    view

Screenshot:

autolayout in Xcode 2016-11-08.png