如何在同一个 class 中使用警报和微调器?

How use alert and spinner in same class?

我将共享 class 用于微调器和警报。它工作正常,但我有时会遇到崩溃问题。

我在 SharedClass

中的代码
import UIKit

class SharedClass: NSObject {

static let sharedInstance = SharedClass()

var transparentView:UIView!
var spinner = UIActivityIndicatorView()

//Show activity indicator
func activityIndicator(view:UIView) {

    DispatchQueue.main.async {
    //            if let window = UIApplication.shared.keyWindow {//Conditionally unwrap it instead of force unwrap

            //let window = UIApplication.shared.keyWindow! //Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
            self.transparentView = UIView()
            self.transparentView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
            self.transparentView.backgroundColor = UIColor.black.withAlphaComponent(0.4)
            view.addSubview(self.transparentView)

            if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad {
                self.spinner = UIActivityIndicatorView(style: .whiteLarge)
                self.spinner.frame = CGRect(x: 0, y: 0, width: 60, height: 60)
            } else {
                self.spinner = UIActivityIndicatorView(style: .white)
                self.spinner.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
            }
            self.spinner.center = view.center
            self.transparentView.addSubview(self.spinner)
            self.spinner.startAnimating()

            DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {//Stop spinner after 10 Sec's
                self.stopActivityIndicator()
            }
        }
//        }
}

//Stop activity indicator
func stopActivityIndicator() {
    DispatchQueue.main.async {
        self.spinner.stopAnimating()
        self.spinner.removeFromSuperview()
        self.transparentView.removeFromSuperview()//Some times getting error here
    }
}

//Present alert on top of all windows
func alertWindow(title: String, message: String) {
    //Calling
    //SharedClass.sharedInstance.alertWindow(title:"", message:"")
    DispatchQueue.main.async(execute: {
        let window = UIWindow(frame: UIScreen.main.bounds)
        window.rootViewController = UIViewController()
        window.windowLevel = UIWindow.Level.alert + 1

        let alert2 = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let defaultAction2 = UIAlertAction(title: "OK", style: .default, handler: { action in
        })
        alert2.addAction(defaultAction2)

        window.makeKeyAndVisible()

        window.rootViewController?.present(alert2, animated: true, completion: nil)
    })
}

private override init() {

}

}

有时我在这一行中遇到错误

let window = UIApplication.shared.keyWindow!//Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

self.transparentView.removeFromSuperview()//Some times getting error here

如何在同一 class 中正确使用这两个警报和微调器。

哪个好用

在共享class中编写代码或在个人class中编写代码。

我在这里写 window 用于在所有 windows 包括导航栏的顶部显示警报和微调器。

不要强制展开,使用if-letguard,像这样:

guard let window = UIApplication.shared.keyWindow else { return }

要修复第二个错误,请使用可选链接

self.transparentView?.removeFromSuperview()

我在我的一个项目中使用了以下方法,这与您的类似,因为我在网络调用期间使用它,它还启用了 NetworkActivity 指示器:

func showActivityIndicator(inView view: UIView? = nil, isNetworkActivityIndicatorVisible: Bool = true) {
    UIApplication.shared.isNetworkActivityIndicatorVisible = isNetworkActivityIndicatorVisible

    guard let target = view ?? UIApplication.shared.keyWindow else { return }

    ...
    let transparentView = UIView()
    // Avoid using self.transparentView here, just use transparentView
    target.addSubview(transparentView)
    self.transparentView = transparentView
}

如果您在 activityIndicator 之前调用 stopActivityIndicator,则 transparentView 将为零。所以不要使用隐式解包可选。

改变

var transparentView:UIView!

var transparentView:UIView?

并在使用此变量时使用可选链接

self.transparentView?.removeFromSuperview()

并使用 guard let 获取密钥 window

guard let window = UIApplication.shared.keyWindow else {
    return
}

警报的 UIViewController 扩展

extension UIViewController {
    func showAlert(title: String, msg: String) {
        DispatchQueue.main.async {
            let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
    }
}

您可以像这样从任何视图控制器调用此方法。它将出现在所有视图和导航栏的顶部。

self.showAlert("Alert", msg: "Alert message")