Reputation: 539
I'm trying to prevent a button from animating when clicked, but I have not been successful.
I've tried setting UIButton.appearance().isHighlighted
, .adjustsImageWhenHighlighted
and .showsTouchWhenHiglighted
, to false
. I've also tried:
Button(action: {}) {
Text("X")
}
.animation(.none)
Upvotes: 5
Views: 3010
Reputation: 1060
The best way to disable it is to provide a custom primitive button style that does not include the default tap animation. Here is the code to accomplish this:
struct NoTapAnimationStyle: PrimitiveButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
// Make the whole button surface tappable. Without this only content in the label is tappable and not whitespace. Order is important so add it before the tap gesture
.contentShape(Rectangle())
.onTapGesture(perform: configuration.trigger)
}
}
Then apply it with this modifier on the button:
.buttonStyle(NoTapAnimationStyle())
Repost of answer here: Disable default button click animation in SwiftUi
Upvotes: 4
Reputation: 257719
Almost, to disable animation in some place we should set nil
, like
Button(action: {}) {
Text("X")
}
.animation(nil) // << here !!
Tested with Xcode 12.1 / iOS 14.1
Upvotes: 1
Reputation: 131418
If you can't get it to work any other way you can disable the button and attach a tap gesture recognizer to it.
Upvotes: 1
Reputation: 1341
I think the purest solution to this problem will be not using Button
.
Instead you can do it like this:
Text("X")
.onTapGesture {
print("clicked!")
}
Upvotes: 5