swiftswiftuiuiviewuikithud

How to show HUD with custom UIView using SwiftUI?


I have looked into HUDContentType and still here is no the case to supports SwiftUI implementation.

How to show SwiftUI View inside PKHUD/HUD?


Solution

  • I have created HUD extension which implements show function with SwiftUI parameter.

    extension HUD {
        public static func show<Content: View>(content: Content, frame: CGRect = .init(x: 0, y: 0, width: 300, height: 400)) {
            let view = UIView(frame: frame)
            let hostView = UIHostingController(rootView: content)
            hostView.view.frame = frame
            view.addSubview(hostView.view)
            let constraints = [
                hostView.view.topAnchor.constraint(equalTo: view.topAnchor),
                hostView.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
                hostView.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
                hostView.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
    
                hostView.view.widthAnchor.constraint(equalTo: view.widthAnchor),
                hostView.view.heightAnchor.constraint(equalTo: view.heightAnchor)
            ]
            view.addConstraints(constraints)
            HUD.show(.customView(view: view))
        }
    }
    

    Usage:

    let alert = Text("SwiftUI Alert Text")
    HUD.show(content: alert)