Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Button tap only on text portion

Tags:

swiftui

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)      } } 
like image 897
RyanTCB Avatar asked Aug 02 '19 21:08

RyanTCB


2 Answers

I think this is a better solution, add the .frame values to the Text() and the button will cover the whole area 😉

Button(action: {     //code }) {     Text("Click Me")     .frame(minWidth: 100, maxWidth: .infinity, minHeight: 44, maxHeight: 44, alignment: .center)     .foregroundColor(Color.white)     .background(Color.accentColor)     .cornerRadius(7) } 
like image 132
Lorenzo R Avatar answered Sep 27 '22 00:09

Lorenzo R


The proper solution is to use the .contentShape() API.

Button(action: action) {   HStack {     Spacer()     Text("My button")     Spacer()   } } .contentShape(Rectangle()) 

You can change the provided shape to match the shape of your button; if your button is a RoundedRectangle, you can provide that instead.

like image 22
Daniel van der Merwe Avatar answered Sep 24 '22 00:09

Daniel van der Merwe