首页 > 解决方案 > AutoLayout 将标签对齐到视图的左侧

问题描述

我是自动布局的新手,就像我的问题一样,当 uilabel 文本增加另一个具有文本nothing消失的标签时,当文本很小时它会出现

当文本很小时

当文本很大时

代码

// first label

let label = UILabel(frame: CGRect(x: 0 , y: 0, width: 10, height: 50))
label.text = "Lorem ipsum dolor sit amet"
label.numberOfLines = 0


view.addSubview(label)

label.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leadingMargin, multiplier: 1.0, constant: 0.0).isActive = true

NSLayoutConstraint(item: label, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailingMargin, multiplier: 1.0, constant: 0.0).isActive = true

NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: view, attribute: .topMargin, multiplier: 1.0, constant: 0.0).isActive = true

// end of first label


// label1

let label1 = UILabel(frame: CGRect(x: 0, y: 0, width: 10, height: 50))

label1.text = "nothing"
label1.numberOfLines = 0
view.addSubview(label1)

label1.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint(item: label1, attribute: .leading, relatedBy: .equal, toItem: label, attribute: .leadingMargin, multiplier: 1.0, constant: label.intrinsicContentSize.width).isActive = true


NSLayoutConstraint(item: label1, attribute: .top, relatedBy: .equal, toItem: view, attribute: .topMargin, multiplier: 1.0, constant: 0.0).isActive = true

// end of label1

标签: iosswiftconstraints

解决方案


问题就在这里

NSLayoutConstraint(item: label1, attribute: .leading,
relatedBy: .equal, toItem: label,
attribute: .leadingMargin, multiplier: 1.0,
constant: label.intrinsicContentSize.width).isActive = true

常数值label.intrinsicContentSize.width使标签消失或离开屏幕,考虑设计

| 10 -leftLabel - 20 - nothingLabel - 10 |

并将 nothingLabel contentCompressionResistencePriority 设置为 1000


推荐阅读