正如你所说,我们已经为label 提供了x, y and height,即
let x: CGFloat = 0
let y: CGFloat = 0
let height: CGFloat = 50
让我们使用上述详细信息创建一个label。还可以根据您的要求将label 的width 设置为UIScreen.main.bounds.width。
let label = UILabel(frame: CGRect(x: x, y: y, width: UIScreen.main.bounds.width, height: height))
label.text = "This is a sample text"
不要忘记将label's translatesAutoresizingMaskIntoConstraints 设置为false 并将其添加到您想要的任何subview。
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
添加label 的相关constraints 及其superview - top, bottom, leading, height。如果需要,您绝对可以添加bottom constraint。这完全取决于您的 UI。
我将label 添加到top of the viewController's view。
NSLayoutConstraint.activate([
label.heightAnchor.constraint(equalToConstant: height),
view.topAnchor.constraint(equalTo: label.topAnchor),
view.leadingAnchor.constraint(equalTo: label.leadingAnchor),
view.trailingAnchor.constraint(equalTo: label.trailingAnchor)
])