Button is not Taking Given Height and Width in SwiftUI

504 views Asked by At

I am new to swiftui. I am making a login screen in which I have to use log in with apple and gmail buttons. I am using a custom view to design the button. Here is the code for that custom button view:

struct CustomSocialButton: View {
    
    var ImgName: String
    
    var body: some View {
        
        
        Button(action: {
                  print("button pressed")

                }) {
                    Image(ImgName)
                    .renderingMode(.original)
                }
        
    }
}

struct CustomSocialButton_Previews: PreviewProvider {
    static var previews: some View {
        CustomSocialButton(ImgName: ImageName.appleSignin.rawValue)
    }
}

I am saving the image names to my constant file.

The problem is when I use it to my actual login view and setting its width and height. It is not taking that height and width. Here is the code for the buttons:

HStack(spacing: 10) {
                   
          CustomSocialButton(ImgName: ImageName.appleSignin.rawValue)
                .frame(width: 48, height: 48)
                   
          CustomSocialButton(ImgName: ImageName.googleSignin.rawValue)
                .frame(width: 48, height: 48)

       }

This is the screenshot of my login View: login view

Does anyone knows what I am doing wrong?

2

There are 2 answers

0
Asperi On BEST ANSWER

You need to make image resizable, like

Image(ImgName)
   .renderingMode(.original)
   .resizable()               // << here !!

also might want to add .aspectRatio(contentMode: .fit)

1
Iskandir On

You can work with Spacer() oder Divider().

Divider will show some horizontally / vertically lines, I dont think that this is your need, so try Spacer().

What does Spacer() do? Spacer is a flexible space that expands with your view. It will "cut down" your horizontally (but also vertically) HStack (VStack) in layout parts. If you like to center a Text you can do it by using

HStack{
    Spacer()
    Text("Hi there");
    Spacer()
}

To resolve your problem, try something like this:

HStack(spacing: 10) {

    CustomSocialButton(ImgName: ImageName.appleSignin.rawValue)
                .frame(width: 48, height: 48)
    Spacer()
    
    CustomSocialButton(ImgName: ImageName.googleSignin.rawValue)
                .frame(width: 48, height: 48)

}