xcodebuttonswiftuiimage-resizingimage-size

Trying to resize a image used for a button label in swiftUI


Im trying to create a Hstack in Swift with two buttons side by side using an image as the label to create coloured buttons.

However i cant work out how to resize an image label.

Ive created an array of Strings linked to images by title

let buttonColours = ["Red", "Green", "Yellow", "Blue", "Grey", "Orange"]

I've then created a Hstack where i've put two buttons side by side

 HStack() {
                    
                    Button{
                        
                    } label: {
                        Image(buttonColours[0])
                    }
                    
              
                    
                    Button{
                        
                        
                    } label: {
                        Image(buttonColours[1])
                    }
                   
                  
                    
                        }

This works just fine until i add the Image labels, but now i cant work out how to change the size of these buttons, i've read elsewhere that i can edit the size of images using

var body: some View {
        Image("myImage")
            .resizable()
            .scaledToFit()
            .frame(width: 200, height: 200)


but i can't seem to use this code to edit the button image / button sizes

ive tried

  Button{
                        
                    } label: {
                        Image(buttonColours[0])
                    } 
                            .resizable()
                            .scaledToFit()
                            .frame(width: 200, height: 200)

and other variations, but i get the error

Value of type 'Button' has no member 'resizable'

Screenshot of my issue


Solution

  • The resizable modifier applies to Image, not Button. You should apply it as follows:

    struct ContentView: View {
        
        var body: some View {
            HStack() {            
                Button{
                    
                } label: {
                    Image(systemName: "questionmark")
                        .resizable()
                        .scaledToFit()
                        .frame(width: 200, height: 200)}
                
                Button{
                    
                    
                } label: {
                    Image(systemName: "doc.on.doc")
                        .resizable()
                        .scaledToFit()
                        .frame(width: 200, height: 200)
                }
            }
        }
    }
    

    enter image description here