gpt4 book ai didi

ios - Swift - 单击按钮后立即显示带有加载指示器的警报的最佳方式?

转载 作者:搜寻专家 更新时间:2023-11-01 05:56:21 25 4
gpt4 key购买 nike

我尝试使用主线程来显示但它没有用,有没有想过为什么警报没有立即显示?

@IBAction func updateData(_ sender: Any) {
let alert = UIAlertController(title: "Updating data", message: "Please wait...", preferredStyle: .alert)
alert.view.tintColor = UIColor.black
let loadingIndicator: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRect(x: 10,y: 5,width: 50, height: 50)) as UIActivityIndicatorView
loadingIndicator.hidesWhenStopped = true
loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
loadingIndicator.startAnimating();

alert.view.addSubview(loadingIndicator)
DispatchQueue.main.async {
self.present(alert, animated: true)

}

最佳答案

UIAlertController 无法自定义,所以对我来说最好的解决方案是创建自定义 UIView XIB,然后在我需要的 ViewController 上实例化它。

XIB View 可能是这样的: XIB View

然后你创建一个 CustomAlertLoadingView.swift 文件,它是 UIView 的子类,将它关联到 XIB 并创建 IBOutlets

要在任何 ViewController 中显示它,只需创建此扩展

extension UIViewController {
func presentAlert(title: String) {
let nib = UINib(nibName: "CustomAlertLoadingView", bundle: nil)
let customAlert = nib.instantiate(withOwner: self, options: nil).first as! CustomAlertLoadingView

customAlert.tag = 12345
customAlert.titleAlertLabel.text = title
customAlert.indicator.startAnimating()


let screen = UIScreen.main.bounds
customAlert.center = CGPoint(x: screen.midX, y: screen.midY)

self.view.addSubview(customAlert)
}
}

使用self.yourViewController.presentAlert(title:"yourTitle")

要关闭警报,请在 UIVIewController 扩展中创建此函数

func dismissCustomAlert() {
if let view = self.view.viewWithTag(12345) {
view.removeFromSuperview()
}
}

然后调用self.yourViewController.dismissCustomAlert

关于ios - Swift - 单击按钮后立即显示带有加载指示器的警报的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42077533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com