我是 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)
我知道我可以在处理程序中标记一些变量...但是有没有更好的方法来获取用户选择的选项?
但我仍然找不到解决方案。
请帮忙
最佳答案
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/