在 SwiftUi 中禁用默认按钮单击动画

Luc*_*cSO 8 animation default button disable swiftui

如何禁用 SwiftUI 和 Swift 5 中的默认按钮单击动画?我尝试添加.animation(.nil)到按钮,没有任何更改。

我知道您可以执行以下操作:

Button(action: {}) { Capsule() }
.buttonStyle(NoAnim())

struct NoAnim: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
    configuration.label
}
Run Code Online (Sandbox Code Playgroud)

有人知道更聪明的方法吗?

Asp*_*eri 6

如果我正确理解了你的问题,那么最好只使用

Capsule()
  .onTapGesture {
    // << action here !!
  }
Run Code Online (Sandbox Code Playgroud)

  • 是否可以通过 Voice Over 或其他辅助选项将此 Capsule 识别为按钮? (2认同)

Eri*_*ele 5

禁用它的最佳方法是提供不包含默认点击动画的自定义原始按钮样式。这是完成此操作的代码:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将此修改器应用到按钮上:

.buttonStyle(NoTapAnimationStyle())
Run Code Online (Sandbox Code Playgroud)