Finding the size of a view adjusted by a UIStackView swift
Asked Answered
A

4

9

A number of views in a UIStackView are adjusted to fit the stack. The views are initialised with no frame because they are resized by the stack view. Is there a way which I can get the size of the views after they have been resized by the stack view?

Analogical answered 6/11, 2015 at 3:1 Comment(1)
This question needs some details to get better answers. 1. Why do you need to know a view's size when it's been resized by a stack view? 2. Where do you need to know when the view is resized? In other words, what code needs to handle the resize? Note that with the proper use of constraints it's very unlikely that you actually need to do anything here.Internode
M
5

The sizes are available after UIStackView.layoutSubviews() finishes. You can subclass UIStackView and override layoutSubviews:

class MyStackView: UIStackView {
    override func layoutSubviews() {
        super.layoutSubviews()
        print("arrangedSubviews now have correct frames")
        // Post a notification...
        // Call a method on an outlet...
        // etc.
    }
}
Melanochroi answered 6/11, 2015 at 3:21 Comment(1)
This is not always true, unfortunately. I've encountered many cases where the geometry of the arranged subviews is not correct after super.layoutSubviews(). In my specific case, I always had to check them on the very next run loop, which is ridiculous.Tupelo
A
3

Yes. In your View's layoutSubviews(). However you need to force the UIStackView to layout first, using stack.layoutIfNeeded() before using its size.

eg:

public override func layoutSubviews() {
        super.layoutSubviews()

        // Force the UIStackView to layout, in order to get the updated width.
        stack.layoutIfNeeded()

        let tabWidth = stack.arrangedSubviews[0].frame.size.width
}
Adler answered 12/5, 2020 at 12:33 Comment(0)
A
0

I think the better way to get a Stackview's subview frame is to use convert.

yourStackView.convert(viewInsideStackView.frame to: parentView)

This will return viewInsideStackView's frame inside parentView's coordinate system.

Abbess answered 28/2, 2017 at 21:1 Comment(1)
This doesn't get the subview's frame after getting adjusted by the stackview though.Tread
W
0

✅ Getting dimensions from UIStackview, helps me a lot.

let myStack = UIStackView(arrangedSubviews: [myView])
myView.setNeedsLayout()
myView.layoutIfNeeded()
print(myView.frame)
Whale answered 21/11, 2023 at 15:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.