我有一个获取推送通知的应用程序,它通常显示一个模式。
当用户出于某种原因显示UIAlertController
时就会出现问题。我得到了著名的
Warning: Attempt to present <ViewController> on <ViewController> which is already presenting <UIAlertController>
我在一个带有单个UIViewController
的基本应用中使用以下代码创建了这种情况:
class ViewController: UIViewController {
var color: UIColor = .red
let alertController = UIAlertController(
title: "Title",
message: nil,
preferredStyle: .alert
)
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = color
let alertButton = UIButton()
alertButton.translatesAutoresizingMaskIntoConstraints = false
alertButton.setTitle("alert", for: .normal)
let alertGesture = UITapGestureRecognizer(
target: self,
action: #selector(alert)
)
alertButton.addGestureRecognizer(alertGesture)
let dismissButton = UIButton()
dismissButton.translatesAutoresizingMaskIntoConstraints = false
dismissButton.setTitle("Dismiss", for: .normal)
let dismissGesture = UITapGestureRecognizer(
target: self,
action: #selector(dismissVC)
)
dismissButton.addGestureRecognizer(dismissGesture)
let modalButton = UIButton()
modalButton.translatesAutoresizingMaskIntoConstraints = false
modalButton.setTitle("modal", for: .normal)
let tapGesture = UITapGestureRecognizer(
target: self,
action: #selector(modal)
)
modalButton.addGestureRecognizer(tapGesture)
view.addSubview(alertButton)
view.addSubview(dismissButton)
view.addSubview(modalButton)
NSLayoutConstraint.activate([
alertButton.leadingAnchor.constraint(equalTo: view.leadingAnchor),
alertButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 50),
dismissButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
dismissButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 50),
modalButton.trailingAnchor.constraint(equalTo: view.trailingAnchor),
modalButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 50),
])
alertController.addAction(UIAlertAction(title: "Yes", style: .cancel, handler: nil))
alertController.addAction(UIAlertAction(title: "No", style: .default, handler: { _ in self.alertController.dismiss(animated: false, completion: nil) }))
}
@objc func dismissVC() {
self.dismiss(animated: false, completion: nil)
}
@objc func alert() {
self.present(alertController, animated: true, completion: nil)
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.modal()
}
}
@objc func modal() {
print("modal")
let newVC = ViewController()
newVC.color = .clear
present(newVC, animated: true, completion: nil)
}
}
因此,我在这里意识到了这个问题,我试图在同一个视图控制器中呈现两个视图控制器。
我将如何解决这个问题?
我也尝试通过UIAlertController
展示模式,但是我很高兴没有奏效(警报被重新定位到了意外的位置),因为那将是一个主要的黑客。
我还尝试过解除UIAlertController
的作用,展示模态,并从该新模态中展示UIAlertController
,但是看起来也不是很好...
我唯一剩下的想法是创建一个队列并仅在解除警报时显示模式。我认为该实现在这里是不必要的。
感谢您的想法