You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击第二个Alert的Reset按钮后Progress HUD不显示的解决方法

解决点击Alert的Reset按钮后MBProgressHUD不显示的问题

我看了你的代码逻辑,问题出在第二个Alert还没完全消失,你就尝试显示MBProgressHUD了。UIAlertAction的回调会在Alert开始执行dismiss动画时立刻触发,这时候Alert还占据着屏幕最上层的窗口层级,导致HUD被遮挡,或者因为UI更新时机的问题无法正常渲染出来。

下面给你两种可靠的解决办法:

方法一:修改Utility的Alert方法,确保Alert消失后再执行回调

这是最推荐的方案,因为它从根源上保证了HUD在Alert完全消失后才显示。你只需要修改showAlertViewWithTextField里的successAction逻辑,先手动dismiss Alert,然后在dismiss的completion闭包里触发success回调:

static func showAlertViewWithTextField(title: String, msg: String, okActionTitle:String, cancelActionTitle:String, success: (() -> Void)? , cancel: (() -> Void)?) {
    let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
    alert.addTextField { (textField) in
        textField.placeholder = "Enter new pin."
    }
    alert.addTextField { (textField) in
        textField.placeholder = "Confirm new pin."
    }
    
    let successAction: UIAlertAction = UIAlertAction(title: okActionTitle, style: .destructive) { action -> Void in
        let textOfFirstTextfield = alert.textFields?[0].text
        print(textOfFirstTextfield)
        
        // 先让Alert消失,完成后再执行后续逻辑
        alert.dismiss(animated: true) {
            success?()
        }
    }
    
    let cancelAction: UIAlertAction = UIAlertAction(title: cancelActionTitle, style: .cancel) { action -> Void in
        cancel?()
    }
    
    alert.addAction(successAction)
    alert.addAction(cancelAction)
    UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
}

方法二:确保HUD的显示在主队列执行(可选补充)

虽然UIAlertAction的回调本身就在主队列,但为了避免其他场景下可能的子队列调用问题,你可以给showGlobalProgressHUD加上主队列的强制调度,保证UI操作都在主线程执行:

static func showGlobalProgressHUD(withTitle title: String?) -> MBProgressHUD? {
    var hud: MBProgressHUD?
    DispatchQueue.main.sync {
        let window: UIWindow? = UIApplication.shared.windows.last
        hud = MBProgressHUD.showAdded(to: window, animated: true)
        hud?.labelText = title
        hud?.dimBackground = true
        hud?.cornerRadius = 7
        hud?.margin = 30
        hud?.detailsLabelFont = UIFont.boldSystemFont(ofSize: 15)
        window?.isUserInteractionEnabled = true
        hud?.isUserInteractionEnabled = true
    }
    return hud
}

这样修改后,当你点击Reset按钮,Alert会先平滑消失,然后HUD就会正常显示出来,同时接口调用也能正常执行。

内容的提问来源于stack exchange,提问作者KEERTHI j

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:17:25