How to prevent button from animating when clicked
Asked Answered
I

4

5

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)
Itis answered 4/11, 2020 at 0:2 Comment(1)
Check out my answer here: #61593953Chagall
W
5

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!")
  }
Wolfenbarger answered 4/11, 2020 at 0:57 Comment(1)
I need to use a button.Itis
C
4

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

Chagall answered 13/9, 2023 at 19:39 Comment(1)
Great solution! Just be aware: This solution will change the default label color from blue to white.Ohl
G
1

If you can't get it to work any other way you can disable the button and attach a tap gesture recognizer to it.

Georgie answered 4/11, 2020 at 2:2 Comment(0)
C
1

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

Cosmonaut answered 4/11, 2020 at 5:20 Comment(2)
I'm using the same environment, but it only works on the first click. After that, the animation returns.Itis
.animation(nil) is now deprecated.Ohl

© 2022 - 2024 — McMap. All rights reserved.