AutoLayout将标签对齐到视图的左侧

时间:2018-06-02 21:29:16

标签: ios swift constraints

我是autolayout的新手,因为在我的问题中,当uilabel文本增加另一个文本nothing消失的标签时,当文本很小时会出现

when text is small

when text is large

代码

// 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

1 个答案:

答案 0 :(得分:0)

问题出在这里

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