Q:

NSLayoutConstraints with visual format doesn't work as expected when in UIScrollView? 

I am putting a UILabel inside a UIScrollView, I'd like to add these constraints to the label:

Top margin is 20
Left margin is 20
Right margin is 20
Label's height is 40

Here's the code I wrote for these constraints using visual format:
let label = UILabel.init(frame: .zero)
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "Some Text"
scrollView.addSubview(label)

let horizontalConstraints = NSLayoutConstraint.constraints(
    withVisualFormat: "H:|-20-[label]-20-|",
    options: [],
    metrics: nil,
    views: ["label": label]
)

let verticalConstraints = NSLayoutConstraint.constraints(
    withVisualFormat: "V:|-20-[label(40)]",
    options: [],
    metrics: nil,
    views: ["label": label]
)

NSLayoutConstraint.activate(horizontalConstraints + verticalConstraints)

But this picture is what I'm getting (can't upload photo because I have low reputations).  I added borders to the views, the blue one is the border of UIScrollView, the red one is the border of the UILabel

A:

Your code isn't correct.  Here is how your code should looks.  And if you use this way of adding constraints, you don't need to activate constraints with special method.  These vertical and horizontal constraints have already activated. 
//horizontal constraints
scrollView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[v0]-20-|", 
options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": label]))

//vertical constraints
scrollView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-20-[v0(40)]", 
options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": label]))

Explanation of syntax:
"H", "V" - horizontal, vertical constraints
"|" - anchor, for example "H:|[v0]" - left anchor
"-20-" - offset, for example "V:|-20-[v0]" - top anchor with offset 20
"[v0(40)]" - this is the size of view, for example "V:[v0(40)]" - height is 40
"[v0]" -  your first view in visual format.  This format can set constraints for several views.  
For example: 
(format: "V:|-16-[v0]-8-[v1(44)]-16-[v2(1)]|", views: ["v0": firstView], ["v1": secondView], ["v2": thirdView])

