要在视图控制器上显示警报,可以使用以下代码。
let a = UIAlertController(title: "Your title", message: "Your message", preferredStyle: .alert)
a.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
// Pressed "OK"
}))
self.present(a, animated: true, completion: { finished in
// Alert shown
})
但是,有多少信息可以适合警报的限制。如果你有更长的时间,创建一个新的视图控制器和模态地呈现它也可以工作。这可让您自定义您想要呈现的信息的方式(例如,使用滚动/页面视图)。您还可以自定义您的视图控制器,使其看起来像一个警报,使其目的更清晰。要以模态方式显示视图控制器,可以使用present
方法。
self.present(otherViewController, animated: true, completion: nil)
一种方法我在通路中,以使警报状态视图控制器呈现较小的视图控制器在当前之一,并改变其模式的演讲风格,让您可以看到基本视图控制器通过它。
let otherVC = self.storyboard?.instantiateViewController(withIdentifier: "OtherViewController") as! OtherViewController
otherVC.modalPresentationStyle = .overCurrentContext
otherVC.view.center = vc.view.center
otherVC.delegate = self //Create a delegate so that you can control actions such as "OK" buttons
self.view.isUserInteractionEnabled = false //Stop the user interacting with the view controller behind the alert
self.present(otherVC, animated: true, completion: nil)
编辑: 您可以委派控制操作,如用行动关闭警报。例如,这可能是你委托的一个例子:
protocol AlertDelegate {
func didCancel()
func didOkay()
}
然后,你可以实现这个像这样:
class RootViewController: UIViewController, AlertDelegate {
func didCancel() { ... }
func didOkay() { ... }
func showAlert() {
...
otherVC.delegate = self
...
}
}
然后在你的警报视图控制器,你可以与委托进行交互。
class MyAlert: UIViewController {
var delegate: AlertDelegate!
@IBAction func cancelButton(sender: UIButton) {
delegate.didCancel()
self.dismiss(animated: true, completion: nil)
}
}
所以,当点击警报视图控制器上的取消按钮时,代表会说,它取消了,和模态视图控制器将被解雇。然后,根视图控制器会收到这个动作,并可以相应地处理它。
我喜欢这个想法。那么我怎么最终关闭overop viewController(otherVC)?而且,与此设置,我可以运行从原来的VC代码,让说,用户在otherVC点击“确定”后otherVC关闭?... 就像我要上originalVC的saveButton打开显示信息的otherVC ...用户在其他VC中点击“OK”,另一个VC关闭/消失,然后我想让其余的'saveButtonTapped'代码从原始VC运行? –
@AkkPiasecki是的,代表在这里派上用场。请参阅我为更多信息所做的修改。 – brimstone
我还有一个问题。当按钮被击中时,你在RootViewController中调用'self.view.isUserInteractionEnabled = false'。显然,一旦按钮运行(“ok”或“cancel”),我需要在另一个VC中设置'self.view.isUserInteractionEnabled = true',但是如何在其他VC的代码中引用RootViewController?我试过了: 'let rootVC = self.storyboard?.instantiateViewController(withIdentifier:“RootViewController”)as! RootViewController',然后在另一个VC的“ok”按钮中输入'rootVC.view.isUserInteractionEnabled = true',但这不起作用。 –