使用NSLayout

时间:2017-08-21 23:27:21

标签: ios iphone swift user-interface nslayoutconstraint

我正在添加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的页面中间,但是如何将其移动到顶部。

2 个答案:

答案 0 :(得分:1)

正如我在评论中所说,如果您需要将标签贴在标签超级视图的顶部,则需要使用titleLabel.superview!.centerYAnchor

错误地使用titleLabel.superview!.topAnchor

替换此

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

通过此

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

答案 1 :(得分:0)

我理解的情况是标签位于centerX和centerY中,您希望它稍后位于superView的顶部。如果是这样,我认为您可以使用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