我想添加另一个按钮,而不是"确定"按钮,该按钮应该只是关闭alert .

var logInErrorAlert: UIAlertView = UIAlertView()
logInErrorAlert.title = "Ooops"
logInErrorAlert.message = "Unable to log in."
logInErrorAlert.addButtonWithTitle("Ok")

如何向此alert 中添加另一个按钮,然后允许它在单击后调用某个函数,比如我们希望新按钮调用:

 retry()

推荐答案

快速的方法是使用新的UIAlertController和闭包:

    // Create the alert controller
    let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)

    // Create the actions
    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
        UIAlertAction in
        NSLog("OK Pressed")
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
        UIAlertAction in
        NSLog("Cancel Pressed")
    }

    // Add the actions
    alertController.addAction(okAction)
    alertController.addAction(cancelAction)

    // Present the controller
    self.presentViewController(alertController, animated: true, completion: nil)

Swift 3:

    // Create the alert controller
    let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)

    // Create the actions
    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
        UIAlertAction in
        NSLog("OK Pressed")
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
        UIAlertAction in
        NSLog("Cancel Pressed")
    }

    // Add the actions
    alertController.addAction(okAction)
    alertController.addAction(cancelAction)

    // Present the controller
    self.present(alertController, animated: true, completion: nil)

Swift相关问答推荐

具有@Published属性的双向数据流动,能够忽略事件

数据不会被ARC删除在swift'

如何在SWIFT中解码Instagram Backup中的字符串?

Variadic泛型与Swift中的值和类型参数包

从任务中打印

如何将新事例添加到枚举中?

为什么这段Swift读写锁代码会导致死锁?

为什么 UITapGestureRecognizer 对于 Swift 集合视图中的单元格图像无法正常工作?

可以使 Swift init 仅可用于 Objective C 吗?

为什么 SwiftUI 中 ForEach 的这个 Select 不起作用?

SwiftUI:按钮的圆形边缘的边框尺寸加倍

如何将变量添加到不属于可解码部分的 struct ?

使用 Async-Await 和 Vapor-Fluent 创建 CRUD 函数 - Swift 5.6

UIButton 配置不更新按钮标题

iOS16 Bug 键盘在表单解雇 SwiftUI 时打破布局

SwiftUI Observed Object 在发布值更改时未更新

.onTapGesture 不适用于 Stepper,仅适用于其文本

Alamofire 会自动存储 cookie 吗?

使用 phimagemanager 将图像保存到自定义相册?

如何在 SwiftUI 中为删除和禁用配置 ContextMenu 按钮?