要在視圖控制器上顯示警報,可以使用以下代碼。
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',但這不起作用。 –