【问题标题】:SwiftUI Animate Image on Button按钮上的 SwiftUI 动画图像
【发布时间】:2020-01-24 11:58:13
【问题描述】:

使用 SwiftUI,我试图在用户单击按钮时显示动画图像并隐藏文本。这是我的代码:

@State private var showingActivity = false

var body: some View {
    Button(action: {
        self.showingActivity.toggle()
    }) { 
        HStack {
            if self.showingActivity {
                Image(systemName: "arrow.2.circlepath")
                    .font(.system(size: 29))
                    .rotationEffect(.degrees(self.showingActivity ? 360.0 : 0.0))
                    .animation(Animation.linear(duration: 1.5).repeatForever(autoreverses: false))
            }
            else {
                Text("Continue")
            }
        }
    }
}

Continue 文本出现,点击后消失(如预期),图像显示,但没有动画。任何想法我可能做错了什么。

谢谢

【问题讨论】:

    标签: image animation button swiftui


    【解决方案1】:

    或者试试这个:

    struct ImageView : View {
    
        @State private var showAction = false
    
        var body: some View {
            Image(systemName: "arrow.2.circlepath")
                .font(.system(size: 29))
                .rotationEffect(.degrees(self.showAction ? 360.0 : 0.0))
                .animation(self.showAction ? Animation.linear(duration: 1.5).repeatForever(autoreverses: false) : nil)
            .onAppear() {
                self.showAction = true
            }
        }
    }
    
    struct ContentView: View {
        @State private var showingActivity = false
    
        var body: some View {
            Button(action: {
                self.showingActivity.toggle()
            }) {
                HStack {
                    if self.showingActivity {
                        ImageView()
                    }
                    else {
                        Text("Continue")
                    }
                }
            }
        }
    }
    

    【讨论】:

    • 嘿,克里斯,你的方法是我已经实施的方法,并且很有效。感谢您的提示。
    【解决方案2】:

    您可以使用.opacity 代替if...else 语句,在这种情况下旋转适用于图像。但是在画布中我仍然看到一些小故障,如果多次点击按钮但我没有在真实设备上尝试(行为可能有其他)。希望对您有所帮助:

    struct AnimatableView: View {
        @State private var showingActivity = false
    
        var body: some View {
            Button(action: {
                self.showingActivity.toggle()
            }) {
                ZStack {
                    Image(systemName: "arrow.2.circlepath")
                        .font(.system(size: 29))
                        .rotationEffect(.degrees(self.showingActivity ? 360.0 : 0.0))
                        .animation(Animation.linear(duration: 1.5).repeatForever(autoreverses: false))
                        .opacity(self.showingActivity ? 1 : 0)
    
                    Text("Continue")
                        .opacity(self.showingActivity ? 0 : 1)
    
                }
    
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-26
      • 1970-01-01
      • 1970-01-01
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多