在新的视图控制器上显示警报
Displaying an alert on a new View Controller
我有一个按钮可以将我发送到另一个 View Controller。我正在尝试的是在下一个视图控制器上显示警报。
在新建控制器的viewDidLoad()
方法中,新建一个UIAlertController
,显示如下
let alertController = UIAlertController(title: "Default Style", message: "A standard alert.", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
// ...
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
// ...
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) {
// ...
}
请注意,此示例取自 NSHipster 网站,该网站提供了有关 iOS 的精彩文章。您可以找到有关 UIAlertController here 的文章。他们还解释了您可以用它做的其他事情 class,例如显示操作 Sheet。
Swift 4
使用您的函数创建一个 extension
of UIViewController
以显示具有所需参数参数的警报
extension UIViewController {
func displayalert(title:String, message:String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction((UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
alert.dismiss(animated: true, completion: nil)
})))
self.present(alert, animated: true, completion: nil)
}
}
现在从你的视图控制器调用这个函数:
class TestViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.displayalert(title: <String>, message: <String>)
}
}
我有一个按钮可以将我发送到另一个 View Controller。我正在尝试的是在下一个视图控制器上显示警报。
在新建控制器的viewDidLoad()
方法中,新建一个UIAlertController
,显示如下
let alertController = UIAlertController(title: "Default Style", message: "A standard alert.", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
// ...
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
// ...
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) {
// ...
}
请注意,此示例取自 NSHipster 网站,该网站提供了有关 iOS 的精彩文章。您可以找到有关 UIAlertController here 的文章。他们还解释了您可以用它做的其他事情 class,例如显示操作 Sheet。
Swift 4
使用您的函数创建一个 extension
of UIViewController
以显示具有所需参数参数的警报
extension UIViewController {
func displayalert(title:String, message:String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction((UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
alert.dismiss(animated: true, completion: nil)
})))
self.present(alert, animated: true, completion: nil)
}
}
现在从你的视图控制器调用这个函数:
class TestViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.displayalert(title: <String>, message: <String>)
}
}