以编程方式创建带有约束的 UILabel?

Creating UILabel programmatically with constraints?

我想做的是在我的代码中每次发生特定操作时以编程方式创建一个新的 UILabel。我知道要给标签的 x、y 和高度,但我不想给它设定宽度。我想约束边,使 UILabel 宽度等于屏幕宽度,如果方向翻转,标签宽度也会改变。

我考虑过使用:

CGRect(x:, y:, width:, height:)

但是,如果我使用它,我必须给它一个设定的宽度,所以我认为它不会起作用。

我也试过使用:

CGPoint(x:, y:)

然后设置前导、尾随和高度锚点,但是,这似乎也不起作用,因为即使它编译了,我在尝试创建新的 UILabel 时遇到错误。

我是 Swift 编程的新手,所以我不确定是否有明显的解决方法。

您可以使用以下代码以编程方式创建 UILabel。

private let label: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.numberOfLines = 0
    label.text = "Hello World"
    return label
}()

然后在你的viewDidLoad()里面

addSubview(label)
NSLayoutConstraint.activate([
    topAnchor.constraint(equalTo: label.topAnchor),
    bottomAnchor.constraint(equalTo: label.bottomAnchor),
    leadingAnchor.constraint(equalTo: label.leadingAnchor),
    trailingAnchor.constraint(equalTo: label.trailingAnchor)
])

正如您所说,我们已经有 x, y and height 个可用于 label,即

let x: CGFloat = 0
let y: CGFloat = 0
let height: CGFloat = 50

让我们使用上述详细信息创建一个 label。还要根据您的要求将 labelwidth 设置为 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)
    ])