How to disable position animation in SwiftUI when button style is animated

I have a simple button style which animates the size of the button when it is pressed.
Unfortunately, this causes the position of the button to animate (which I don't want).

Is there a way to limit the animation only to the scale? I have tried surrounding the offending animation with .animation(nil) and .animation(.none) modifiers - but that didn't work.

Code Block Swift
import SwiftUI
struct ExampleBackgroundStyle: ButtonStyle {
 
  func makeBody(configuration: Self.Configuration) -> some View {
    configuration.label
      .padding()
      .foregroundColor(.white)
      .background(Color.red)
      .cornerRadius(40)
      .padding(.horizontal, 20)
      .animation(nil)
      .scaleEffect(configuration.isPressed ? 0.6 : 1.0)
      .animation(.easeIn(duration: 0.3))
      .animation(nil)
  }
}


when I show a button in a sheet, it animates in from the top left (0,0) to the position in the centre of the sheet after the sheet appears.

If I remove the animation on the scaleEffect, then this doesn't happen.


  • I have the same problem, my animation is just color change, and all moves up and down.

Add a Comment

Replies

I have the same problem, any solution appreciated
add in viewModel class:
@Published var viewAppear = false
add init:
init() {
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
      self.viewAppear = true
    }
  }
In view:
 .animation(viewModel.viewAppear ? .linear : nil)