I have a subclass of UIStackView
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)
}
}
On the ViewController
I create an instance of this class
let myStack = MyStack()
myStack.setupSymbols(5)
self.view.addSubview(myStack)
print (myStack.frame)
the last line gives me width and height equal to zero!!!
why?
CodePudding user response:
The frame of the view won't be updated until the next layout pass. The frame doesn't get calculated immediately after adding the view to the view hierarchy, that's why you see it being zero.
If you override the view controller's viewDidLayoutSubviews
method and check the frame there, it will likely be non-zero.