UIAlertController + UIProgressView + macCatalyst

UIAlertController + UIProgressView + macCatalyst

我使用以下简单的 class 在我的 iOS 应用程序中显示带有进度条的警报视图。没问题,但是当我尝试在为 macOS 构建的应用程序中使用相同的代码时,进度条不可见(见附图)。

我应该如何更改才能在 macOS 上也有进度条?

protocol ProgressDelegate: class {
    func onProgressCanceled()
}

class ProgressAlert {

private let alert: UIAlertController
private var progressBar: UIProgressView

init(title: String, delegate: ProgressDelegate?) {
    
    alert = UIAlertController(title: title, message: "",
                              preferredStyle: .alert)
    
    progressBar = UIProgressView(progressViewStyle: .default)
    progressBar.tintColor = Theme.appColor
    
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { alertAction in
        delegate?.onProgressCanceled()
    })
}

func present(from uivc: UIViewController) {
    
    uivc.present(alert, animated: true, completion: {
        
        let margin: CGFloat = 16.0
        let rect = CGRect(x: margin, y: 56.0,
                          width: self.alert.view.frame.width - margin * 2.0, height: 2.0)
        self.progressBar.frame = rect
        self.alert.view.addSubview(self.progressBar)
    })
}

func dismiss(completion: (() -> Void)?) {
    
    alert.dismiss(animated: true, completion: completion)
}

func setProgress(_ value: Float) {
    progressBar.setProgress(value, animated: true)
    print("Updating download: \(value)")
}
}

进度条实际上是按预期添加的,但是 Mac Catalyst 完全隐藏了 UIAlertController 视图并显示了原生 macOS NSAlert

您可以通过将 alert.view.isHidden 设置为 false 来查看带有进度条的原始警报:

请记住,您一开始就不应该向警报控制器添加自定义视图。引用自 docs:

Important

The UIAlertController class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified.