Reputation: 6775
I am new to Swift and iOS development. I am trying to get sort method from ActionSheet. Here's my code:
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)
I understand that I can mark some variable in handler...but is there any better way to get the selected option by the user?
I have read this: https://developer.apple.com/library/ios/documentation/Uikit/reference/UIAlertController_class/index.html#//apple_ref/occ/instm/UIAlertController/addAction
but still I can't find a solution.
Please help
Upvotes: 0
Views: 1311
Reputation: 852
swift takes a new approach when dealing with alert views/action sheets. when you add an UIAlertAction
to your UIAlertController
there is a parameter called handler
. this is the code (called closure), which will be called when user selects one of the actions on your action sheet.
the final code can look something like this
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))]
you can (and should) read more about closures here
Upvotes: 2