SwiftUI 让View自动消失

Max*_*x B 0 swiftui

我有一个由按钮触摸触发的视图。看起来不错,一切都很好。现在我希望视图在几秒钟后再次自动消失。

视图应该自动消失,无需再次点击按钮。

下面是我的测试项目

import SwiftUI  

struct ContentView: View {  
  @State private var presentClipboardView = false  
  @State private var scale: CGFloat = 1.0  


  var body: some View {  
  VStack{  
  Button(action: {  
  let pasteboard = UIPasteboard()  
  pasteboard.string = "http://I_AM_A_URL.com"  

  withAnimation(.easeInOut(duration: 2)) {  
  self.presentClipboardView.toggle()  
  }  
  }, label: {  
  HStack {  
  Image(systemName: "list.dash")  
  .padding(.trailing)  
  VStack(alignment: .leading) {  
  Text("Open URL")  
  .font(.headline)  
  }  

  Spacer()  
  }  
  }  
  )  
  if(self.presentClipboardView){  
  LabelView()  
  }  
  }  

  }  
}  

struct ContentView_Previews: PreviewProvider {  
  static var previews: some View {  
  ContentView()  
  }  
}  

struct LabelView: View {  
  var body: some View {  
  Text("URL copied to clipboard!")  
  .padding(10)  
  .font(.title)  
  .foregroundColor(.white)  
  .background(RoundedRectangle(cornerRadius: 8).fill(Color.green).shadow(color: .gray, radius: 3))  
  }  
}  
Run Code Online (Sandbox Code Playgroud)

Sor*_*ica 6

在 LabelView() 上试试这个

LabelView().onAppear {
                        Timer.scheduledTimer(withTimeInterval: 3, repeats: false) { timer in
                            withAnimation(.easeInOut(duration: 2)) {
                                self.presentClipboardView.toggle()
                            }
                        }
                    }
Run Code Online (Sandbox Code Playgroud)