Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the size of a view adjusted by a UIStackView swift

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?

like image 960
Matt Spoon Avatar asked Nov 06 '15 03:11

Matt Spoon


2 Answers

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.
    }
}
like image 174
rob mayoff Avatar answered Nov 19 '22 09:11

rob mayoff


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
}
like image 40
MihaiL Avatar answered Nov 19 '22 10:11

MihaiL