Search code examples
swiftui

is it possible to adjust RoundedRectangle's width according to Button label's width?


I have this Button with RoundedRectangle, and it has fixed width (and height), but I want to calculate the width based on the Button's content. Is it possible?

ZStack {
    RoundedRectangle(cornerRadius: 12)
        .frame(width: 170, height: 50) // <- I want this WIDTH to be calculated
    
    Button {
        viewModel.startNewGame()
    } label: {
        Text("New Game")
        Image(systemName: "return")
    }
    .font(.title2)
    .foregroundStyle(.white)
}

I was thinking of using Geometry Reader, but I am new to SwiftUI.


Solution

  • Instead of using ZStack try background

            Button {
            } label: {
                Text("New Game")
                Image(systemName: "return")
            }
            .font(.title2)
            .foregroundStyle(.white)
            .padding()
            .background {
                RoundedRectangle(cornerRadius: 12)
            }