快速警报视图(iOS8),单击确定和取消按钮,点击该按钮

B_s*_*B_s 100 xcode alert dialog confirmation swift

我在Swift编写的Xcode中有一个警报视图,我想确定用户选择哪个按钮(它是一个确认对话框)什么都不做或执行某些操作.目前我有:

@IBAction func pushedRefresh(sender: AnyObject) {
        var refreshAlert = UIAlertView()
        refreshAlert.title = "Refresh?"
        refreshAlert.message = "All data will be lost."
        refreshAlert.addButtonWithTitle("Cancel")
        refreshAlert.addButtonWithTitle("OK")
        refreshAlert.show()
    }
Run Code Online (Sandbox Code Playgroud)

我可能使用错误的按钮,请更正我,因为这对我来说都是新的.

谢谢!

Mic*_*uth 294

如果您使用的是iOS8,则应使用UIAlertController - 不推荐使用UIAlertView .

以下是如何使用它的示例:

var refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.Alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
  print("Handle Ok logic here")
  }))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action: UIAlertAction!) in
  print("Handle Cancel Logic here")
  }))

presentViewController(refreshAlert, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,UIAlertAction的块处理程序处理按钮按下.这里有一个很棒的教程(虽然本教程不是用swift编写的):http: //hayageek.com/uialertcontroller-example-ios/

Swift 3更新:

let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
    print("Handle Ok logic here")
}))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
    print("Handle Cancel Logic here")
}))

present(refreshAlert, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)

  • 您可以在示例中使用`UIAlertActionStyle.Cancel`而不是`.Default`. (4认同)
  • 为较新的 Swift 版本更新答案真是太好了 (4认同)

A.G*_*A.G 17

var refreshAlert = UIAlertController(title: "Log Out", message: "Are You Sure to Log Out ? ", preferredStyle: UIAlertControllerStyle.Alert)

refreshAlert.addAction(UIAlertAction(title: "Confirm", style: .Default, handler: { (action: UIAlertAction!) in
    self.navigationController?.popToRootViewControllerAnimated(true)
}))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in

    refreshAlert .dismissViewControllerAnimated(true, completion: nil)


}))

presentViewController(refreshAlert, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)