Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get size of a given element (eg. button)

I am trying to get the size of a button. The button’s frame size is dynamic based on the text size. How can I do this?

I tried wrapping this in a GeometryReader, and reading the geo.size.height, etc, but this returned 10 every time, and messed up the layout (somehow actually gave the button that height).

I don’t know a way to do this that doesn’t involve GeometryReader, have searched and found nothing.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Button(action: {
    //
}) {
    Text(options[i])
        .font(.system(.headline, design: .rounded))
        .frame(maxWidth: .infinity, alignment: .leading)
        .foregroundColor(Color.init(red: 0.3, green: 0.3, blue: 0.3))
    .frame(alignment: .leading)
    .padding()
    .background(
        RoundedRectangle(cornerRadius: 12)
            .fill(Color.white)
    )
}

>Solution :

To get the size of a view, add a GeometryReader as a .background. This needs to contain another view, and when that appears you have

Button(action: {
    //
}) {
    Text("something")
        .font(.system(.headline, design: .rounded))
        .frame(maxWidth: .infinity, alignment: .leading)
        .foregroundColor(Color.init(red: 0.3, green: 0.3, blue: 0.3))
    .frame(alignment: .leading)
    .padding()
    .background(
        RoundedRectangle(cornerRadius: 12)
            .fill(Color.white)
    )
    
    .background {
        GeometryReader { proxy in
            Color.clear
                .onAppear {
                    print(proxy.size)
                }
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading