Mostafa Sultan
Mostafa Sultan

Reputation: 2438

make Button action cover it's superview swiftUI

i need to make a button that fills it's container view and make all the view clickable, but i failed, it only make button content size clickable (which is the label size)

Button(action: {
       print("item Clicked")
       }) {
       Text("whyyyy")
}.frame(maxWidth: .infinity, maxHeight: .infinity).buttonStyle(PlainButtonStyle())

i know i can reverse it by putting my container view within the button but i just don't like this style i need the button to be within the view and i know i can make a tapGesture but i want to feel free like in UIKit

Upvotes: 0

Views: 276

Answers (2)

Alex Giatrakis
Alex Giatrakis

Reputation: 375

Just move .frame(maxWidth: .infinity, maxHeight: .infinity) under Text("whyyyy") before before closing the bracket

Edit: Also add the modifier .background(Color.clear)

Final Result:

Button(action: {
       print("item Clicked")
       }) {
       Text("whyyyy")
          .frame(maxWidth: .infinity, maxHeight: .infinity)
          .background(Color.clear)
}

Upvotes: 0

Raja Kishan
Raja Kishan

Reputation: 18914

You can use clear color content to make whole area clickable.

struct ContentViewNewTest: View {
    var body: some View {
        ZStack {
            Color.red
            Button(action: {
                print("item Clicked")
            }) {
                Color.clear //<--- Here
            }
        }
    }
}

Upvotes: 1

Related Questions