ios - 返回在 UIAlertControllerStyle.ActionSheet 中选择的 Action

标签 ios swift uialertcontroller

我是 Swift 和 iOS 开发新手。 我正在尝试从 ActionSheet 获取排序方法。 这是我的代码:

    var alert = UIAlertController(title: "Sort", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)

    alert.addAction(UIAlertAction(title: "Price: Low to High", style: UIAlertActionStyle.Default, handler: nil))

    alert.addAction(UIAlertAction(title: "Latest", style: UIAlertActionStyle.Default, handler: nil))

    alert.addAction(UIAlertAction(title: "Price: High to Low", style: UIAlertActionStyle.Default , handler: nil))

    alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))

    self.presentViewController(alert, animated: true, completion: nil)

我知道我可以在处理程序中标记一些变量...但是有没有更好的方法来获取用户选择的选项?

我读过这个:https://developer.apple.com/library/ios/documentation/Uikit/reference/UIAlertController_class/index.html#//apple_ref/occ/instm/UIAlertController/addAction

但我仍然找不到解决方案。

请帮忙

最佳答案

swift 在处理警报 View /操作表时采用了一种新方法。当您将 UIAlertAction 添加到您的 UIAlertController 时,会有一个名为 handler 的参数。这是代码(称为闭包),当用户在您的操作表上选择一个操作时将调用它。 最终代码看起来像这样

enum SortType {
    case PriceLowToHigh, Latest, PriceHighToLow
}

func sort(sortType: SortType) {
    //do your sorting here depending on type
}

var alert = UIAlertController(title: "Sort", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)

alert.addAction(UIAlertAction(title: "Price: Low to High", style: UIAlertActionStyle.Default) { (_) -> Void in sort(SortType.PriceLowToHigh) } )

alert.addAction(UIAlertAction(title: "Latest", style: UIAlertActionStyle.Default) { (_) -> Void in sort(SortType.Latest) } )

alert.addAction(UIAlertAction(title: "Price: High to Low", style: UIAlertActionStyle.Default) { (_) -> Void in sort(SortType.PriceHighToLow) } )

alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))]

您可以(并且应该)阅读更多关于闭包的信息 here

关于ios - 返回在 UIAlertControllerStyle.ActionSheet 中选择的 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27248643/

相关文章:

ios - 打字时缩小 BackSpace 上的 UITextField 范围

ios - 如何使用 iOS8 在 UIAlertController 中设置 UITableView 的位置和大小

ios - 将按钮放在 UIImageView 的右上角

ios - 自定义初始化程序而不覆盖 init?

ios - 在 Swift 中使用 Objective-C 类时出现 "Cannot Find Initializer"

ios - UIAlert 无法将类型 '(_) throws -> ()' 的值转换为预期的参数类型 '((UIAlertAction) -> Void)?'

ios - BarButtonItem 上显示的 UIAlertController 未正确居中

ios - 升级到 Swift 2.0 时出现段错误 11

ios - iOS应用程序中的youtube iFrame在全屏后导致半屏变黑

ios - 将 String 转换为二进制时缺少一位