Ios 返回在UIAlertControllerStyle.ActionSheet中选择的操作
我是Swift和iOS开发的新手。 我正在尝试从ActionSheet获取排序方法。 这是我的密码:Ios 返回在UIAlertControllerStyle.ActionSheet中选择的操作,ios,swift,uialertcontroller,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: UIAlertAction
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在处理警报视图/行动表时采用了新方法。将
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))]
您可以(并且应该)阅读有关闭包的更多信息谢谢@kap…我会尝试一下…您能解释一下如何使用“actions”变量吗?不客气。您指的是哪个变量?类UIAlertController:UIViewController{var actions:[AnyObject]{get}}命令单击UIAlertController…您可以在developer.apple.com上阅读“actions”的描述,您根本不必使用它。只需添加操作并显示操作表。当用户点击一个按钮时,相关代码将被调用。我理解您的解决方案…但在我学习的过程中,我想知道变量的意义…谢谢!