如何使用Swift iOS向UIAlertView按钮添加动作

前端之家收集整理的这篇文章主要介绍了如何使用Swift iOS向UIAlertView按钮添加动作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想添加“确定”按钮以外的其他按钮,该按钮应该只是关闭警报.
我想要另一个按钮来调用某个功能.
  1. var logInErrorAlert: UIAlertView = UIAlertView()
  2. logInErrorAlert.title = "Ooops"
  3. logInErrorAlert.message = "Unable to log in."
  4. logInErrorAlert.addButtonWithTitle("Ok")

如何在此警报中添加另一个按钮,然后允许它在点击后调用一个函数,让我们说我们想要调用新按钮:

  1. retry()
Swifty方式是使用新的UIAlertController和闭包:
  1. // Create the alert controller
  2. let alertController = UIAlertController(title: "Title",message: "Message",preferredStyle: .Alert)
  3.  
  4. // Create the actions
  5. let okAction = UIAlertAction(title: "OK",style: UIAlertActionStyle.Default) {
  6. UIAlertAction in
  7. NSLog("OK Pressed")
  8. }
  9. let cancelAction = UIAlertAction(title: "Cancel",style: UIAlertActionStyle.Cancel) {
  10. UIAlertAction in
  11. NSLog("Cancel Pressed")
  12. }
  13.  
  14. // Add the actions
  15. alertController.addAction(okAction)
  16. alertController.addAction(cancelAction)
  17.  
  18. // Present the controller
  19. self.presentViewController(alertController,animated: true,completion: nil)

斯威夫特3:

  1. // Create the alert controller
  2. let alertController = UIAlertController(title: "Title",preferredStyle: .alert)
  3.  
  4. // Create the actions
  5. let okAction = UIAlertAction(title: "OK",style: UIAlertActionStyle.default) {
  6. UIAlertAction in
  7. NSLog("OK Pressed")
  8. }
  9. let cancelAction = UIAlertAction(title: "Cancel",style: UIAlertActionStyle.cancel) {
  10. UIAlertAction in
  11. NSLog("Cancel Pressed")
  12. }
  13.  
  14. // Add the actions
  15. alertController.addAction(okAction)
  16. alertController.addAction(cancelAction)
  17.  
  18. // Present the controller
  19. self.present(alertController,completion: nil)

猜你在找的Swift相关文章