2014-12-02 2 views
0

Я новичок в разработке Swift и iOS. Я пытаюсь получить метод сортировки из ActionSheet. Вот мой код:Вернуть действие, выбранное в UIAlertControllerStyle.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

, но до сих пор я не могу найти решение.

Пожалуйста, помогите

ответ

0

быстр принимает новый подход при работе с видами предупреждений листов/действий. когда вы добавляете 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

+0

благодаря @kap ... Я постараюсь, что ... Можете ли вы объяснить, как использовать переменную «действия»? – sasquatch

+0

добро пожаловать. на какую переменную вы ссылаетесь? – kap

+0

класс UIAlertController: UIViewController { действия вар: [AnyObject] {получить}} команда щелкните UIAlertController ... Вы можете прочитать описание «действий» на developer.apple.com – sasquatch