JonasGessner / JGProgressHUD

An elegant and simple progress HUD for iOS and tvOS, compatible with Swift and ObjC.
MIT License
3.35k stars 336 forks source link

SwiftUI Example #135

Closed c941010623 closed 4 years ago

c941010623 commented 4 years ago
  1. Create File.
  2. Use this demo code.
  3. Have fun.
import SwiftUI
import JGProgressHUD

class ProgressHUDController: UIViewController {
    let hud = JGProgressHUD(style: .dark)

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.dismiss()
    }

    func show(text: String) {
        hud.textLabel.text = text
        hud.show(in: self.view)
    }

    func dismiss() {
        print("dismiss ~~~")
        hud.dismiss()
    }
}

struct ProgressHUD: UIViewControllerRepresentable {
    func makeUIViewController(context: UIViewControllerRepresentableContext<ProgressHUD>) -> ProgressHUDController {
        ProgressHUDController()
    }

    func updateUIViewController(_ uiViewController: ProgressHUDController, context: UIViewControllerRepresentableContext<ProgressHUD>) {
        uiViewController.show(text: "Loading ...")
    }

    typealias UIViewControllerType = ProgressHUDController
}

public struct ProgressHUDView<Content>: View where Content: View {
    private var isShowing: Binding<Bool>
    private var content: () -> Content

    public init(isShowing: Binding<Bool>, content: @escaping () -> Content) {
        self.isShowing = isShowing
        self.content = content
    }

    public var body: some View {
        ZStack(alignment: .center) {
            if (!self.isShowing.wrappedValue) {
                self.content()
            } else {
                self.content()
                    .disabled(true)
                    .blur(radius: 3)

                ProgressHUD()
            }
        }
    }
}

struct ProgressView: View {
    @State var isShow: Bool = false

    var body: some View {
        ProgressHUDView(isShowing: self.$isShow) {
            Button(action: {
                self.isShow.toggle()
                DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(2000)) {
                    self.isShow.toggle()
                }
            }) {
                Text("Try Me!")
            }
        }
    }
}

struct ProgressView_Previews: PreviewProvider {
    static var previews: some View {
        ProgressView()
    }
}
JonasGessner commented 4 years ago

I appreciate your effort to make this compatible with SwiftUI. Posting an example code for others is not what issues are for though and I will close this issue. I encourage you to fork the repository though, add a SwiftUI example to the example project or to even add a wrapper for SwiftUI to the main library, and then open a pull request.