【问题标题】:SwiftUI: How to delete a view after a certain timeSwiftUI:如何在一段时间后删除视图
【发布时间】:2022-08-18 18:43:27
【问题描述】:

我有这个动画代码:

struct CheckmarkAnimation: View {
    @State private var isAnimating = false

    var body: some View {
        ZStack {
            Circle()
                .trim(to: isAnimating ? 1:0)
                .stroke(.green, lineWidth: 3)
                .frame(width: 100, height: 100)
                .animation(.easeInOut(duration: 1), value: isAnimating)
            
            Image(systemName: \"checkmark\")
                .foregroundColor(.green)
                .font(.largeTitle)
                .scaleEffect(isAnimating ? 1.5 : 0)
                .animation(.spring(response: 0.5, dampingFraction: 0.4).delay(1), value: isAnimating)
        }
        .onAppear {
            isAnimating.toggle()
        }
    }
}

我希望这个视图在复选标记上的缩放效果结束后消失。我该怎么做呢?

  • 哪种观点?如果您的意思是CheckmarkAnimation,那么它不应该在这里,而是在父视图中。
  • 您可能有另一个布尔值shouldAppear,并使用DispatchQueue.main.asyncAfter(deadline:execute:) 来切换它。
  • 谢谢! DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {shouldAppear = true} 完成这项工作。

标签: ios swift swiftui


【解决方案1】:

这是一种让它消失的方法(变成不可见但仍然占用空间)。 2秒后将绘图颜色更改为.clear

struct CheckmarkAnimation: View {
    @State private var isAnimating = false
    @State private var color = Color.green
    
    var body: some View {
        ZStack {
            Circle()
                .trim(to: isAnimating ? 1:0)
                .stroke(color, lineWidth: 3)
                .frame(width: 100, height: 100)
                .animation(.easeInOut(duration: 1), value: isAnimating)
            
            Image(systemName: "checkmark")
                .foregroundColor(color)
                .font(.largeTitle)
                .scaleEffect(isAnimating ? 1.5 : 0)
                .animation(.spring(response: 0.5, dampingFraction: 0.4).delay(1), value: isAnimating)
                
        }
        .onAppear {
            isAnimating.toggle()
            withAnimation(.linear(duration: 0.01).delay(2)) {
                color = .clear
            }
        }
    }
}

【讨论】:

  • 谢谢你,它也有效!
猜你喜欢
  • 2020-10-02
  • 2014-06-21
  • 2020-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-29
  • 2020-01-20
相关资源
最近更新 更多