Swift UIKit-显示一个又一个警报



我正试图在swift中显示一个又一个警报。我找到了一个解决方案,但我认为这不是真正的方法。我的代码在下面。

使用此代码,可以在视图中显示警报

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let person = people[indexPath.item]

let questionAc = UIAlertController(title: "What is your purpose?", message: "", preferredStyle: .alert)
let deleteButton = UIAlertAction(title: "Delete", style: UIAlertAction.Style.destructive) { [weak self] _ in

self?.people.remove(at: indexPath.item)
collectionView.reloadData()
}

let renameButton = UIAlertAction(title: "Rename", style: .default) { [weak self] _ in

let ac = UIAlertController(title: "Rename person", message: nil, preferredStyle: .alert)
ac.addTextField()
ac.addAction(UIAlertAction(title: "Cancel", style: .cancel))
ac.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak self, weak ac] _ in
guard let newName = ac?.textFields?[0].text else {return}
person.name = newName
self?.collectionView.reloadData()
}))
self?.present(ac, animated: true)

}

questionAc.addAction(deleteButton)
questionAc.addAction(renameButton)
present(questionAc, animated: true) 
}

正如你所知,如果我直接在第一个代码之后添加我的警报代码,它是不起作用的。但如果我把我的第二个代码放在第一个的动作上,它确实会。

然而,在这种情况下,我需要将一个警报连接到另一个按钮的操作。我不想把它连接到另一个。

有没有更好的解决方案可以在同一视图中有序地显示警报?

谢谢。

当在第一个警报的某个操作的处理程序中完成时,显示第二个警报是有效的,因为处理程序是在警报解除后执行的。

考虑到这一点,您只需要解除第一个警报,然后在解除呼叫的完成块中显示第二个警报,例如:

(在这里,我们只需等待2.5秒就可以显示第二个警报(

func showAlert1() {
let alert = UIAlertController(title: "Alert!", message: "I am alert number 1", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Action", style: .default, handler: { _ in
print("Alert 1 action pressed")
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
present(alert, animated: true)
// Wait 2.5 seconds then dismiss the first alert and present the second alert
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(2500), execute: { [weak self] in
alert.dismiss(animated: true) {
self?.showAlert2()
}
})
}

如果您希望第一个警报保持打开状态(以便在第二个警报解除时仍然可见(,您可以将第一个警报用作呈现的ViewController,例如:

func showAlert1() {
let alert = UIAlertController(title: "Alert!", message: "I am alert number 1", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Action", style: .default, handler: { _ in
print("Alert 1 action pressed")
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
// Wait 2.5 seconds then present the second alert
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(2500), execute: {
self.showAlert2(from: alert)
})
present(alert, animated: true)
}
func showAlert2(from viewController: UIViewController) {
let alert = UIAlertController(title: "Alert!", message: "I am alert number 2", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Action", style: .default, handler: { _ in
print("Alert 2 action pressed")
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
viewController.present(alert, animated: true)
}

最新更新