当我在SwiftUI中实现一个Button时,当您单击它时,此Button始终具有标准动画。轻微的不透明动画。有办法摆脱这种动画吗? 这是一个简单的例子。
这是一个小视频-> https://imgur.com/ClWd7YH
import SwiftUI
struct ContentView: View {
var body: some View {
VStack{
Button(action: {
// do somethinh
}) {
VStack{
ZStack{
Circle()
.fill(Color.white)
.frame(width: 45, height: 45, alignment: .center)
Image(systemName: "xmark.circle")
.foregroundColor(Color.black)
.font(Font.system(size: 18, weight: .thin))
.padding(6)
}
Text("Press")
.foregroundColor( Color.white)
}.frame(width: 300, height: 300, alignment: .center)
}
}.background(Color.green)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
答案 0 :(得分:1)
您可以通过创建自己的buttonStyle
获得所需的内容。这样,您必须指定要在点击时使用的动画。如果您不指定任何动画,则按钮将没有任何动画。例如:
struct NoAnimationButton: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
}
}
struct ContentView: View {
var body: some View {
VStack{
Button(action: {
// do somethinh
}) {
VStack{
ZStack{
Circle()
.fill(Color.white)
.frame(width: 45, height: 45, alignment: .center)
Image(systemName: "xmark.circle")
.foregroundColor(Color.black)
.font(Font.system(size: 18, weight: .thin))
.padding(6)
}
Text("Press")
.foregroundColor( Color.white)
}
.frame(width: 300, height: 300, alignment: .center)
}
}
.background(Color.green)
.buttonStyle(NoAnimationButton())
}
}
考虑到您始终可以避免使用Button
视图,并在整个可点击视图(或任何需要的位置)上实现onTapGesture
:
struct ContentView: View {
var body: some View {
VStack{
VStack{
ZStack{
Circle()
.fill(Color.white)
.frame(width: 45, height: 45, alignment: .center)
Image(systemName: "xmark.circle")
.foregroundColor(Color.black)
.font(Font.system(size: 18, weight: .thin))
.padding(6)
}
Text("Press")
.foregroundColor( Color.white)
}
.frame(width: 300, height: 300, alignment: .center)
}
.background(Color.green)
.onTapGesture {
//manage click
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
编辑:仅举一个带有动画的buttonStyle
的示例:
struct ScaleEffectButton: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.scaleEffect(configuration.isPressed ? 0.9 : 1)
}
}
答案 1 :(得分:1)
您可以定义自己的ButtonStyle
,它将覆盖默认动画:
public struct ButtonWithoutAnimation: ButtonStyle {
public func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
}
}
现在只需在Button
上设置样式:
Button(action: { .. } {
..
}.buttonStyle(ButtonWithoutAnimation())