blksld
blksld

Reputation: 129

SwiftUI Size Struct by .frame modifier

Hello I got a Custom Button Struct which has an Image and a Text and also a Style for that Button, which is added at the end of the Struct. My Question is: Is there any way I can use the .frame(width: , height: ) and .frame(minWidth: maxWidth) modifier, without passing a variable to the struct which then passes it to the button style?

CustomButton:

struct CustomButtonWithImage: View {
let title: String
let image: String
let action: () -> Void

var body: some View {
    Button(action: action) {
        HStack {
            Image(image)
                .resizable()
                .renderingMode(.template)
                .frame(maxWidth: imageSize.width, maxHeight: imageSize.height)
                .aspectRatio(contentMode: .fit)
            Text(title)
                .font(.system(size: fontSize))
                .bold()
                .minimumScaleFactor(0.8)
                .lineLimit(1)
        }
        .padding(.horizontal, horizontalPadding)
    }
    .buttonStyle(CustomButtonStyle(size: buttonSize)) // <- Button Style
    .accentColor(Color.white)
}

}

struct CustomButtonStyle: ButtonStyle {

func makeBody(configuration: Self.Configuration) -> some View {
    configuration
        .label
        .contentShape(Rectangle())
        .foregroundColor(Color.white)
        .accentColor(Color.white)
        .background(Color("CustomButtonColor"))
}

}

Basically I just want to Do this:

var body: some View {
    VStack {
        CustomButton(text: "hello": image("someImage.png") { print("hello") }
            // Is there a way to set this without passing the struct a var or let?
            // I can set this but this wont make the button bigger, because the label in the button style wont change size with this
            .frame(width: 40, height: 50)
            .frame(maxWidth: ..., maxHeight: ...)
    }
}

}

Upvotes: 1

Views: 552

Answers (1)

Asperi
Asperi

Reputation: 257779

Remove hardcoded frame and add max allowed, so it will consume available space shrank only by other views layout. Also you can use only one, either maxWidth or maxHeight restriction if needed.

CustomButton(text: "hello": image("someImage.png") { print("hello") }
//    .frame(width: 40, height: 50)    // remove hardcode
    .frame(maxWidth: .infinity, maxHeight: .infinity)  // << max allowed

Upvotes: 1

Related Questions