ViewController 在呈现警报控制器时重新加载 swift

ViewController reloads on presenting alert controller swift

我正在做项目。我在单击注册按钮时添加了一个简单的 alertController。当我单击按钮时,我的 viewcontroller 重新加载,然后它显示 alertController.它发生在 iOS 13 和 swift 5 或更高

    let alert = UIAlertController(title: "Your title", message: "Your message", preferredStyle: .alert)

     let ok = UIAlertAction(title: "OK", style: .default, handler: { action in
     })
     alert.addAction(ok)
     let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { action in
     })
     alert.addAction(cancel)
     DispatchQueue.main.async(execute: {
        self.present(alert, animated: true)
})

我通过这几行代码解决了我的问题

func alert(message: String, title: String = "") {
            let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
            let alertAction = UIAlertAction(title: "OK", style: .default) { (action) in
                print("Action")
            }
            alertController.addAction(alertAction)
           (UIApplication.shared.delegate as! AppDelegate).alertWindow.isHidden = true

            self.presentViewController(alertController: alertController)
    //        self.present(alertController, animated: true, completion:  nil)

        }
    func presentViewController(alertController: UIAlertController, completion: (() -> Void)? = nil) {
        if var topController = UIApplication.shared.keyWindow?.rootViewController {
            while let presentedViewController = topController.presentedViewController {
                topController = presentedViewController
            }

            DispatchQueue.main.async {
                topController.present(alertController, animated: true, completion: completion)
            }
        }
    }