UIStackView 边界在创建后为零
UIStackView bounds is zero after creation
我有一个 UIStackView
的子class
final class MyStack : UIStackView {
required init(coder: NSCoder) {
super.init(coder: coder)
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
private func setup() {
backgroundColor = .clear
axis = .horizontal
contentMode = .scaleAspectFit
alignment = .fill
distribution = .fillProportionally
spacing = 0
contentMode = .scaleToFill
isUserInteractionEnabled = true
autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin, .flexibleWidth, .flexibleHeight]
translatesAutoresizingMaskIntoConstraints = true
}
func setupSymbols(_ amount:Int) {
let large = UIImage.SymbolConfiguration(scale: .large)
for index in 0..< number {
let image = UIImage(systemName: "trash", withConfiguration: large)
let highlightedImage = UIImage(systemName: "trash.fill", withConfiguration: large)
let imageView = UIImageView(image: image, highlightedImage: highlightedImage)
self.addArrangedSubview(oneStar)
}
}
在 ViewController
我创建了这个 class
的一个实例
let myStack = MyStack()
myStack.setupSymbols(5)
self.view.addSubview(myStack)
print (myStack.frame)
最后一行让我的宽度和高度等于零!!!
为什么?
直到下一个布局阶段,视图的框架才会更新。将视图添加到视图层次结构后不会立即计算框架,这就是为什么您看到它为零的原因。
如果您覆盖视图控制器的 viewDidLayoutSubviews
方法并检查那里的框架,它可能是 non-zero。
我有一个 UIStackView
的子classfinal class MyStack : UIStackView {
required init(coder: NSCoder) {
super.init(coder: coder)
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
private func setup() {
backgroundColor = .clear
axis = .horizontal
contentMode = .scaleAspectFit
alignment = .fill
distribution = .fillProportionally
spacing = 0
contentMode = .scaleToFill
isUserInteractionEnabled = true
autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin, .flexibleBottomMargin, .flexibleWidth, .flexibleHeight]
translatesAutoresizingMaskIntoConstraints = true
}
func setupSymbols(_ amount:Int) {
let large = UIImage.SymbolConfiguration(scale: .large)
for index in 0..< number {
let image = UIImage(systemName: "trash", withConfiguration: large)
let highlightedImage = UIImage(systemName: "trash.fill", withConfiguration: large)
let imageView = UIImageView(image: image, highlightedImage: highlightedImage)
self.addArrangedSubview(oneStar)
}
}
在 ViewController
我创建了这个 class
let myStack = MyStack()
myStack.setupSymbols(5)
self.view.addSubview(myStack)
print (myStack.frame)
最后一行让我的宽度和高度等于零!!!
为什么?
直到下一个布局阶段,视图的框架才会更新。将视图添加到视图层次结构后不会立即计算框架,这就是为什么您看到它为零的原因。
如果您覆盖视图控制器的 viewDidLayoutSubviews
方法并检查那里的框架,它可能是 non-zero。