在SwiftUI中禁用默认按钮点击动画

12

我怎样才能在SwiftUI和Swift 5中禁用默认的按钮点击动画? 我尝试向按钮添加 .animation(.nil),但没有任何变化。

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

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

struct NoAnim: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
    configuration.label
}

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

3个回答

18

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

Capsule()
  .onTapGesture {
    // << action here !!
  }

2
您是否可以使用Voice Over或其他辅助选项来识别此Capsule作为按钮的用户? - lucaszischka
根据胶囊的内容,这个解决方案可能会有很多不可点击的空间。 - undefined

3

iOS 13.x,Swift 5。

如果你想要一个可点击但不是按钮的东西,只需使用带有onTapGesture的标签,然后您可以添加任何您喜欢的动画。

或者您也可以像这样使用onDrag手势。这将在您触摸它时立即更新dragLocation,因此它就像是触摸事件。它也没有任何与其相关的动画。如果您愿意,可以添加它们。

Text("Hello World")
.accessibility(label: Text("Button"))
.gesture(
    DragGesture(minimumDistance: 5, coordinateSpace: .global)
        .onChanged { value in
          self.dragLocation = value.location
        }
        .onEnded { _ in
          self.dragLocation = .zero
        }
)

您是否使用Voice Over或其他辅助选项来识别此标签作为按钮? - lucaszischka
Lucas。您可以添加许多标签到您的代码中,以使其更易于访问。这些选项需要使用.accessability修饰符进行特定添加。我已经在上面测试了VoiceOver,并编辑了代码,以便在您经过文本时宣布按钮。但是,在相关/不同的注意事项上,最好使用此网站的方法是发布单独的问题。您可以发表任意数量的帖子。为了获得最佳答案,请在特定帖子中提出有关可访问性的具体问题。 - user3069232

2
最好的方法是提供一个自定义的原始按钮样式,不包含默认的点击动画。以下是实现这一点的代码:
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)
    }
}

然后在按钮上使用这个修饰符。
.buttonStyle(NoTapAnimationStyle())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接