为什么当我将 UIStackView 分布设置为 equalspacing 时子视图不可见?
Why are subviews not visible when I set UIStackView distribution to equalspacing?
我想将一组自定义视图水平放置在 UIStackView
中。
每个子视图都有宽度和高度 equal to constant
约束:
let stack = UIStackView(frame: frameRect)
stack.axis = UILayoutConstraintAxis.horizontal
stack.distribution = UIStackViewDistribution.equalSpacing
stack.layoutMargins = UIEdgeInsets(top: 0, left: 40, bottom: 0, right: 40)
stack.isLayoutMarginsRelativeArrangement = true
for i in 1...3 {
let numberView = RotatingNumberView()
numberView.heightAnchor.constraint(equalToConstant: CGFloat(cellSize))
numberView.widthAnchor.constraint(equalToConstant: CGFloat(cellSize))
numberViews.append(numberView)
stack.addArrangedSubview(numberView)
}
如果我更改为 fillEqually
分布,则会显示子视图,但它们的宽度会被拉伸以填充 stackView。
我猜是和hugging或者compression resistance priority有关系,但是在subview里设置这些都不行。
这里发生了什么?
对于除 fillEqually
之外的所有分布,堆栈视图在计算沿堆栈轴的大小时使用每个排列视图的 intrinsicContentSize
属性。
所以重写这个 属性 会起作用。
override var intrinsicContentSize: CGSize { return CGSize(your values) }
我想将一组自定义视图水平放置在 UIStackView
中。
每个子视图都有宽度和高度 equal to constant
约束:
let stack = UIStackView(frame: frameRect)
stack.axis = UILayoutConstraintAxis.horizontal
stack.distribution = UIStackViewDistribution.equalSpacing
stack.layoutMargins = UIEdgeInsets(top: 0, left: 40, bottom: 0, right: 40)
stack.isLayoutMarginsRelativeArrangement = true
for i in 1...3 {
let numberView = RotatingNumberView()
numberView.heightAnchor.constraint(equalToConstant: CGFloat(cellSize))
numberView.widthAnchor.constraint(equalToConstant: CGFloat(cellSize))
numberViews.append(numberView)
stack.addArrangedSubview(numberView)
}
如果我更改为 fillEqually
分布,则会显示子视图,但它们的宽度会被拉伸以填充 stackView。
我猜是和hugging或者compression resistance priority有关系,但是在subview里设置这些都不行。
这里发生了什么?
对于除 fillEqually
之外的所有分布,堆栈视图在计算沿堆栈轴的大小时使用每个排列视图的 intrinsicContentSize
属性。
所以重写这个 属性 会起作用。
override var intrinsicContentSize: CGSize { return CGSize(your values) }