Search code examples
swiftui

SwiftUI Button tap only on text portion


The background area of my button is not detecting user interaction. Only way to interact with said button is to tap on the Text/ Label area of the button. How to make entire Button tappable?

struct ScheduleEditorButtonSwiftUIView: View {

    @Binding  var buttonTagForAction : ScheduleButtonType
    @Binding  var buttonTitle        : String
    @Binding  var buttonBackgroundColor : Color


    let buttonCornerRadius = CGFloat(12)

    var body: some View {

        Button(buttonTitle) {
              buttonActionForTag(self.buttonTagForAction)
        }.frame(minWidth: (UIScreen.main.bounds.size.width / 2) - 25, maxWidth: .infinity, minHeight: 44)

                            .buttonStyle(DefaultButtonStyle())
                            .lineLimit(2)
                            .multilineTextAlignment(.center)
                            .font(Font.subheadline.weight(.bold))
                            .foregroundColor(Color.white)

                            .border(Color("AppHighlightedColour"), width: 2)
                           .background(buttonBackgroundColor).opacity(0.8)

                            .tag(self.buttonTagForAction)
                            .padding([.leading,.trailing], 5)
       .cornerRadius(buttonCornerRadius)

    }
}

Solution

  • This fixes the issue on my end:

    var body: some View {
        GeometryReader { geometry in
            Button(action: {
                // Action
            }) {
                Text("Button Title")
                    .frame(
                        minWidth: (geometry.size.width / 2) - 25,
                        maxWidth: .infinity, minHeight: 44
                    )
                    .font(Font.subheadline.weight(.bold))
                    .background(Color.yellow).opacity(0.8)
                    .foregroundColor(Color.white)
                    .cornerRadius(12)
    
            }
            .lineLimit(2)
            .multilineTextAlignment(.center)
            .padding([.leading,.trailing], 5)
        }
    }
    

    button

    Is there a reason why you are using UIScreen instead of GeometryReader?