【发布时间】:2018-06-22 06:15:35
【问题描述】:
这是我的层次结构:
- 将包含行的垂直 Stackview (mystack)
- 视图、包装器(父视图)
- 将包含两个标签的水平 Stackview (stacktmp)
- 标签 x2 (tx, tx2)
另外:mystack 有 4 个约束:前导、尾随、顶部和底部与“安全视图”相同。
代码:
let parentview = UIView()
parentview.backgroundColor = UIColor.cyan
let stacktmp = UIStackView()
stacktmp.axis = .horizontal
let tx = UILabel()
tx.text = "ss"
tx.backgroundColor = UIColor.red
tx.font = UIFont.boldSystemFont(ofSize: 19)
let tx2 = UILabel()
tx2.text = "This is a long sentence to check whether the view and the stackview adapt successfully to the length of this label."
//tx2.numberOfLines = 0
stacktmp.addArrangedSubview(tx)
stacktmp.addArrangedSubview(tx2)
parentview.addSubview(stacktmp)
stacktmp.translatesAutoresizingMaskIntoConstraints = false
print(parentview.frame.size.height)
stacktmp.topAnchor.constraint(equalTo: parentview.topAnchor).isActive = true
stacktmp.heightAnchor.constraint(equalTo: parentview.heightAnchor).isActive = true
mystack.addArrangedSubview(parentview)
stacktmp.trailingAnchor.constraint(equalTo: parentview.trailingAnchor, constant: 0).isActive = true
stacktmp.leadingAnchor.constraint(equalTo: parentview.leadingAnchor, constant: 0).isActive = true
我得到了什么:
我的目标:
如果需要,我希望第二个标签的句子将单词分开并在下面多行填写。
我尝试添加以下行:tx2.numberOfLines = 0(在代码中注释)
结果我得到了:
它确实按照我的意愿拆分了句子,但现在第一个标签不必要地扩展了。
如何在保持第一个标签尽可能窄的同时允许第二个标签在必要时使用多行?我已经尝试修复这个问题几个小时了,已经尝试更改约束,但我仍然无法修复它。
【问题讨论】:
-
您要查找的内容称为 HuggingPriority 和 CompressionResistance。一开始可能很难理解,但是有很多博客文章可以让它更容易 - 只需谷歌它。
标签: swift autolayout