SwiftUI: Button is clickable outside its frame

180 Views Asked by At

I am making log in button for log in page. I have this problem: outside (below, right or left) of the button area, button still gets clicked. How I fix this? I want this button to get clicked when I click inside its frame.

import SwiftUI

struct LoginScreenView: View {
    var body: some View {
        VStack {
            Spacer()
            Button {
               //TODO
            } label: {
                LoginButton(textLabel: "Log in")
            }
            Spacer()
        }
    }
}

struct LoginScreenView_Previews: PreviewProvider {
    static var previews: some View {
        LoginScreenView()
    }
}

struct LoginButton: View {
    let textLabel: String
    var body: some View {
        
        HStack {
            Text(textLabel)
                .font(.navTitle)
                .foregroundColor(.white)
                .padding()
                .padding(.vertical, 5)
                .padding(.horizontal, 100)
                .background(Color(.blue))
                .cornerRadius(10)
        }
    }
}

when I click close to this button it gets tapped, even though I am not clicking on the button itself(blue area)

1

There are 1 best solutions below

2
Hing Tat Tsang On
struct LoginScreenView: View {
    var body: some View {
        VStack {
            Spacer()
            Button {
                // TODO
            } label: {
                LoginButton(textLabel: "Log in")
                    .contentShape(Rectangle()) // Define the clickable area of the button
            }
            Spacer()
        }
    }
}