An elaboration on Mundi's answer.
i.e. embedding a label in a UIView
and enforcing padding through Auto Layout. Example:
Overview:
1) Create a UIView
("panel"), and set its appearance.
2) Create a UILabel
and add it to the panel.
3) Add constraints to enforce padding.
4) Add the panel to your view hierarchy, then position the panel.
Details:
1) Create the panel view.
let panel = UIView()
panel.backgroundColor = .green
panel.layer.cornerRadius = 12
2) Create the label, add it to the panel as a subview.
let label = UILabel()
panel.addSubview(label)
3) Add constraints between the edges of the label and the panel. This forces the panel to keep a distance from the label. i.e. "padding"
Editorial: doing all this by hand is super-tedious, verbose and error-prone. I suggest you pick an Auto Layout wrapper from github or write one yourself
label.panel.translatesAutoresizingMaskIntoConstraints = false
label.topAnchor.constraint(equalTo: panel.topAnchor,
constant: vPadding).isActive = true
label.bottomAnchor.constraint(equalTo: panel.bottomAnchor,
constant: -vPadding).isActive = true
label.leadingAnchor.constraint(equalTo: panel.leadingAnchor,
constant: hPadding).isActive = true
label.trailingAnchor.constraint(equalTo: panel.trailingAnchor,
constant: -hPadding).isActive = true
label.textAlignment = .center
4) Add the panel to your view hierarchy and then add positioning constraints. e.g. hug the right-hand side of a tableViewCell, as in the example image.
Note: you only need to add positional constraints, not dimensional constraints: Auto Layout will solve the layout based on both the intrinsicContentSize
of the label and the constraints added earlier.
hostView.addSubview(panel)
panel.translatesAutoresizingMaskIntoConstraints = false
panel.trailingAnchor.constraint(equalTo: hostView.trailingAnchor,
constant: -16).isActive = true
panel.centerYAnchor.constraint(equalTo: hostView.centerYAnchor).isActive = true