使用 NSLayout 设置 UILabel 的 X 和 Y 值

Set X and Y values of UILabel using NSLayout

我正在添加一个 UI 标签,我正在尝试编程 UI 代码。我使用以下代码设置标签:

let titleLabel: UILabel = {
    let lb = UILabel()
    lb.translatesAutoresizingMaskIntoConstraints = false
    lb.textAlignment = .center
    lb.numberOfLines = 1
    lb.textColor = UIColor.black
    lb.font=UIFont.systemFont(ofSize: 22)
    lb.backgroundColor = UIColor.white
    return lb

然后使用此代码添加约束:

func setupTitleLabel() {


    titleLabel.translatesAutoresizingMaskIntoConstraints = false
    titleLabel.heightAnchor.constraint(equalToConstant: 100).isActive = true
    titleLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true
    titleLabel.centerXAnchor.constraint(equalTo: titleLabel.superview!.centerXAnchor).isActive = true
    titleLabel.centerYAnchor.constraint(equalTo: titleLabel.superview!.centerYAnchor).isActive = true
}

我稍后调用这个函数。但是,我不确定如何更改为 X 和 Y 值。目前,它被设置为 X 和 Y 的页面中间,但我如何将它移到顶部。

我理解的情况是标签在 centerX 和 centerY,你希望它在 superView 的顶部 later.If 所以,我想你可以使用 var centerYAnchor: NSLayoutConstraint?

centerYAnchor = titleLabel.centerYAnchor.constraint(equalTo: titleLabel.superview!.centerYAnchor)
centerYAnchor.isActive = true

以后想改变标签在顶部的时候,可以设置centerYAnchor.isActive = false并设置标签的topAnchor。

 titleLabel.topAnchor.constraint(equalTo: titleLabel.superview!.topAnchor).isActive = true

正如我在评论中所说,如果您需要将标签固定到标签超级视图的顶部,您使用的 titleLabel.superview!.centerYAnchor 是错误的,您需要使用 titleLabel.superview!.topAnchor 而不是

替换这个

titleLabel.centerYAnchor.constraint(equalTo: titleLabel.superview!.centerYAnchor).isActive = true

由此

titleLabel.centerYAnchor.constraint(equalTo: titleLabel.superview!.topAnchor).isActive = true