Search code examples
iosswiftnslayoutconstraint

What is system spacing in a layout?


I'm having difficulty understanding what "system spacing" or "standard spacing" between views are.

import UIKit
import PlaygroundSupport

let rootView = UIView(frame: CGRect(x: 100, y: 100, width: 500, height: 500))
rootView.backgroundColor = .white

let containerView = UIView(frame: CGRect(origin: .zero, size: .init(width: 300, height: 200)))
containerView.backgroundColor = .yellow
rootView.addSubview(containerView)

let button = UIButton()
button.setTitle("Button", for: .normal)
button.backgroundColor = .red
containerView.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
    button.widthAnchor.constraint(equalToConstant: 100),
    button.leadingAnchor.constraint(equalToSystemSpacingAfter: containerView.leadingAnchor, multiplier: 1)
])

PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = rootView

I noticed that there is a difference if I substituted:

button.leadingAnchor.constraint(equalTo: containerView.leadingAnchor)

for equalToSystemSpacingAfter in the position of the button. Also, how does equalToSystemSpacingAfter accommodate changes in the text size?


Solution

  • Answer to first question:

    difference between constraint(equalTo: & .constraint(equalToSystemSpacingAfter:

    enter image description here enter image description here

    Answer to second question:

    Also, how does equalToSystemSpacingAfter accommodate changes in the text size?

    Since you are using fixed width of 100 points, so if the button title grows in length, it will be simply truncated. To solve the issue, you should avoid setting exact width of it.