提醒Swift 4

一键式

class ViewController: UIViewController { 
  @IBAction func showAlertButtonTapped(_ sender: UIButton) { 
  // create the alert 
let alert = UIAlertController(title: "My Title", message: "This is my message.", preferredStyle: UIAlertControllerStyle.alert)
  // add an action (button) 
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
  // show the alert 
self.present(alert, animated: true, completion: nil)
}
}

两个按钮

 class ViewController: UIViewController { 
  @IBAction func showAlertButtonTapped(_ sender: UIButton) { 
  // create the alert 
let alert = UIAlertController(title: "UIAlertController", message: "Would you like to continue learning how to use iOS alerts?", preferredStyle: UIAlertControllerStyle.alert)
  // add the actions (buttons) 
alert.addAction(UIAlertAction(title: "Continue", style: UIAlertActionStyle.default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
  // show the alert 
self.present(alert, animated: true, completion: nil)
}
}

三个按钮

 class ViewController: UIViewController { 
  @IBAction func showAlertButtonTapped(_ sender: UIButton) { 
  // create the alert 
let alert = UIAlertController(title: "Notice", message: "Lauching this missile will destroy the entire universe. Is this what you intended to do?", preferredStyle: UIAlertControllerStyle.alert)
  // add the actions (buttons) 
alert.addAction(UIAlertAction(title: "Remind Me Tomorrow", style: UIAlertActionStyle.default, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Launch the Missile", style: UIAlertActionStyle.destructive, handler: nil))
  // show the alert 
self.present(alert, animated: true, completion: nil)
}
}

处理按钮水龙头

在以上示例中, handlernil 。 您可以将nil替换为闭包,以在用户点击按钮时执行某些操作。 例如:

 alert.addAction(UIAlertAction(title: "Launch the Missile", style: UIAlertActionStyle.destructive, handler: { action in 
  // do something like... 
self.launchMissile()
 })) 

笔记

  • 多个按钮不一定需要使用不同的UIAlertActionStyle类型。 它们都可以是.default
  • 对于三个以上的按钮,请考虑使用操作表。 设置非常相似。

对于:Suragch on StackOverFlow