Let's say, you have a label which height is calculated based on it's superview height dimension.
var label: UILabel!
You can anchor the height of the label like
// enable auto-layout
label.translatesAutoresizingMaskIntoConstraints = false
// add label into super view
view.addSubview(label)
// calculate height and activate constraint
label.heightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.heightAnchor, constant: 0.1).isActive = true // calculate height based on super view safe area layout guide
You can active constraints using the following method also (instead of .isActive = true):
let superHeight = view.frame.height
NSLayoutConstraint.activate([
label.heightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.heightAnchor, constant: 0.1), // 10% of super view height
label.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: superHeight * 0.1)
])
Set the other constraints as per your requirements.
Let's take an example:
private let testLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "Test"
label.numberOfLines = 0 // can be multiple line based on content
label.textAlignment = .center
label.textColor = .gray
return label
}()
private func labelSetup() {
view.addSubview(testLabel)
let heightSuperView = view.frame.height
NSLayoutConstraint.activate([
testLabel.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 8),
testLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: heightSuperView*0.1),
testLabel.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -8)
])
}
call labelSetup() method inside viewDidLoad(), You will get the expected output.