Activity indicator in SwiftUI

后端 未结 9 2034
忘了有多久
忘了有多久 2020-11-29 17:36

Trying to add a full screen activity indicator in SwiftUI.

I can use .overlay(overlay: ) function in View Protocol.

With this, I c

9条回答
  •  旧巷少年郎
    2020-11-29 18:37

    I implemented the classic UIKit indicator using SwiftUI. See the activity indicator in action here

    struct ActivityIndicator: View {
      @State private var currentIndex: Int = 0
    
      func incrementIndex() {
        currentIndex += 1
        DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(50), execute: {
          self.incrementIndex()
        })
      }
    
      var body: some View {
        GeometryReader { (geometry: GeometryProxy) in
          ForEach(0..<12) { index in
            Group {
              Rectangle()
                .cornerRadius(geometry.size.width / 5)
                .frame(width: geometry.size.width / 8, height: geometry.size.height / 3)
                .offset(y: geometry.size.width / 2.25)
                .rotationEffect(.degrees(Double(-360 * index / 12)))
                .opacity(self.setOpacity(for: index))
            }.frame(width: geometry.size.width, height: geometry.size.height)
          }
        }
        .aspectRatio(1, contentMode: .fit)
        .onAppear {
          self.incrementIndex()
        }
      }
    
      func setOpacity(for index: Int) -> Double {
        let opacityOffset = Double((index + currentIndex - 1) % 11 ) / 12 * 0.9
        return 0.1 + opacityOffset
      }
    }
    
    struct ActivityIndicator_Previews: PreviewProvider {
      static var previews: some View {
        ActivityIndicator()
          .frame(width: 50, height: 50)
          .foregroundColor(.blue)
      }
    }
    
    

提交回复
热议问题