美文网首页
在SwiftUI中自定义Toast

在SwiftUI中自定义Toast

作者: 漆黑烈焰武士G | 来源:发表于2022-02-06 00:55 被阅读0次

    一、背景

    二、代码

    • 使用方法:

      import SwiftUI
      
      struct ContentView: View {
          
          @State var showToast = false
          
          var body: some View {
              Button(action: {
                  self.showToast.toggle()
              }, label: {
                  Text("Button")
              })
              .toast(isShow: $showToast, info: "请求成功")
          }
      }
      

      该Toast会在其所在的View上居中展示,请妥善选择Toast所在的View

    • Toast源码:

      import SwiftUI
      
      struct TWToastView: View {
          @Binding var isShow: Bool
          let info: String
          @State private var isShowAnimation: Bool = true
          @State private var duration : Double
          
          init(isShow:Binding<Bool>,info: String = "", duration:Double = 1.0) {
              self._isShow = isShow
              self.info = info
              self.duration = duration
          }
          
          var body: some View {
              ZStack {
                  Text(info)
                      .font(Font.title3)
                      .foregroundColor(.white)
                      .frame(minWidth: 80, alignment: Alignment.center)
                      .zIndex(1.0)
                      .padding()
                      .background(
                          RoundedRectangle(cornerRadius: 12)
                              .foregroundColor(.black)
                              .opacity(0.6)
                      )
                  
              }
              .onAppear() {
                  DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
                      isShowAnimation = false
                  }
              }
              .padding()
              .opacity(isShowAnimation ? 1 : 0)
              .animation(.easeIn(duration: 0.8))
              .edgesIgnoringSafeArea(.all)
              .onChange(of: isShowAnimation) { e in
                  DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
                      self.isShow = false
                  }
              }
          }
      }
      
      extension View {
          func toast(isShow:Binding<Bool>, info:String = "",  duration:Double = 1.0) -> some View {
              ZStack {
                  self
                  if isShow.wrappedValue {
                      TWToastView(isShow:isShow, info: info, duration: duration)
                  }
              }
           }
      }
      

      可根据实际需要进行自定义修改

    相关文章

      网友评论

          本文标题:在SwiftUI中自定义Toast

          本文链接:https://www.haomeiwen.com/subject/rotukrtx.html