ios - 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
解决方案
问题就在这里
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
推荐阅读
- javascript - 将 Hooks 函数导出为 react 组件的正确方法是什么?
- java - 有没有办法从哈希图中找到重复值,即 ArrayList?
- c++ - ShowWindow 仅在最后一次最小化时恢复窗口
- c - gprof 显示 0 计算时间
- angular - 如何在 ng-select 自定义标签上使用复制/粘贴
- javascript - Vue 和 firebase 未捕获类型错误:snapshot.forEach 不是函数
- c# - 如何将字节数组从 C# 传递到外部 DLL
- java - 使用 Java 计算 PI 近似值
- python - 聚合熊猫数据框中的相同连接行(时间序列组)
- javascript - 使用 vanilla js 获取 json 字符串中键的总和