ios - 为什么 UIStackView 不堆叠 UILabelarrangedSubview?

标签 ios uilabel uistackview

我有一个 UIStackView,作为排列的 subview ,我有两个 UIView 和一个 UILabel。 UIViews 一个接一个堆叠,而 UILabel 与 subview 的前缘对齐。

代码:

let stack = UIStackView()
stack.axis = .horizontal
stack.distribution = .fillProportionally
stack.alignment = .center
stack.spacing = 7
view.addSubview(stack)
stack.translatesAutoresizingMaskIntoConstraints = false
stack.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
stack.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

let icon = UIView()
icon.backgroundColor = UIColor.red
stack.addArrangedSubview(icon)
icon.translatesAutoresizingMaskIntoConstraints = false
icon.heightAnchor.constraint(equalToConstant: 42).isActive = true
icon.widthAnchor.constraint(equalToConstant: 42).isActive = true

let icon2 = UIView()
icon2.backgroundColor = UIColor.red
stack.addArrangedSubview(icon2)
icon2.translatesAutoresizingMaskIntoConstraints = false
icon2.heightAnchor.constraint(equalToConstant: 42).isActive = true
icon2.widthAnchor.constraint(equalToConstant: 42).isActive = true

let label = UILabel()
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0
label.sizeToFit()
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = .yellow
label.text = "Hello World! Again"
label.textColor = .black
stack.addArrangedSubview(label)

输出: enter image description here

最佳答案

为了清楚起见...

首先,不要使用.fillProportionally。无论你认为那会做什么,那都是错误的。您已明确将两个“图标”的宽度分别设置为 42 磅。如果堆栈 View 使用 .fillProportionally,它将尝试更改这些 View 的宽度,并且您将遇到自动布局冲突。

其次,.numberOfLines = 0UILabel 必须具有宽度。否则,无法知道在哪里中断文本...如果有大量文本,它会延伸到 View 两侧。

第三,label.sizeToFit()行在这里不会完成任何事情。删除它即可。

如果添加此行:

stack.widthAnchor.constraint(equalToConstant: 200.0).isActive = true

然后堆栈 View 将扩展到 200 点宽...

自动布局将为第一个排列 View 提供 42 的宽度(因为这就是您声明的宽度),第二个 View 也是如此。由于您已将间距设置为 7,因此它将计算

42 + 7 + 42 + 7

等于98。它从堆栈 View 的宽度中减去该宽度:

200 - 98 = 102

是标签的宽度。

结果:

enter image description here

如果您不想将宽度显式设置为200,则可以将其设置为 super View 宽度的百分比,或者为其指定前导和尾随约束。

关于ios - 为什么 UIStackView 不堆叠 UILabelarrangedSubview?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49580513/

相关文章:

ios - iOS 应用程序的图标文件

ios - Xcode 根据按钮在新 View 中加载数据

IOS:在不剪裁模糊的情况下向 UIImage 添加模糊

ios - UITableView 中的动态标签宽度

objective-c - 如何在堆栈 View 中设置容器的高度?

ios - Swift 3 - 根据 mp3 的长度自动滚动 UITextView

ios - 如何使大写字母的 UILabel NSUnderlineStyle.StyleSingle attributedString 居中

ios - 在 UITableView 内以编程方式将 UIView 添加到 UIStackView

ios - UIStackView : Is it really necessary to call both removeFromSuperView and removeArrangedSubview to remove a subview?

iphone - 在 iOS 中选择 UILabel 时推送到另一个 View Controller