Home > Software engineering >  How to get size of a given element (eg. button)
How to get size of a given element (eg. button)

Time:01-28

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.

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)
    )
}

CodePudding user response:

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)
                }
        }
    }
}
  • Related