UIActionSheet с быстрым

Я создал лист действий, но проблема в том, что метод делегата не вызывается

 myActionSheet = UIActionSheet()
        myActionSheet.addButtonWithTitle("Add event")
        myActionSheet.addButtonWithTitle("close")
        myActionSheet.cancelButtonIndex = 1
        myActionSheet.showInView(self.view)

/// UIActionSheetDelegate

func actionSheet(myActionSheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int){
        if(myActionSheet.tag == 1){

            if (buttonIndex == 0){
                println("the index is 0")
            }
        }
}

Я использовал другой способ, который хорошо работал с iOS 8, но не работал с iOS 7:

var ActionSheet =  UIAlertController(title: "Add View", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)

ActionSheet.addAction(UIAlertAction(title: "Add event", style: UIAlertActionStyle.Default, handler:nil))

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

Любая идея решить проблему?


person moteb    schedule 11.06.2014    source источник
comment
Лист действий и представление предупреждений устарели в iOS 8, и появился alertController.   -  person nikhil84    schedule 23.06.2014
comment
Да, это устарело, но если вы поддерживаете свое приложение для iOS 7, то alertController не будет работать. Так что лучше проверьте версию iOS и вызовите соответствующий код для iOS 8 и iOS 7.   -  person Mahmud Ahsan    schedule 03.05.2015
comment
Взгляните на этот ответ - stackoverflow. ком/вопросы/27787777/   -  person Kampai    schedule 02.07.2015


Ответы (5)


Вы никогда не устанавливаете делегат листа действий:

myActionSheet = UIActionSheet()
myActionSheet.delegate = self
person Ian Henry    schedule 11.06.2014

UIActionSheet на быстром языке: -

Лист действий с CancelButton и destroyButton

установите UIActionSheetDelegate.

        let actionSheet = UIActionSheet(title: "ActionSheet", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: "Done")
        actionSheet.showInView(self.view)

Лист действий с cancelButton , destroyButton и otherButton

        let actionSheet = UIActionSheet(title: "ActionSheet", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: "Done", otherButtonTitles: "Yes", "No")
        actionSheet.showInView(self.view)

создать функцию листа действий

func actionSheet(actionSheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int)
{
    switch buttonIndex{

    case 0:
        NSLog("Done");
        break;
    case 1:
        NSLog("Cancel");
        break;
    case 2:
        NSLog("Yes");
        break;
    case 3:
        NSLog("No");
        break;
    default:
        NSLog("Default");
        break;
        //Some code here..

 }
person Anit Kumar    schedule 04.09.2014
comment
Я написал версию Swift, которая не полагается на жестко закодированные индексы кнопок для другого ответа: stackoverflow.com/a/29272140/37168 - person stone; 28.03.2015

UIActionSheet устарела с iOS8, я бы рекомендовал использовать UIAlertController, если вам не нужно поддерживать версию ниже:

private func presentSettingsActionSheet() {
  let settingsActionSheet: UIAlertController = UIAlertController(title:nil, message:nil, preferredStyle:UIAlertControllerStyle.ActionSheet)
  settingsActionSheet.addAction(UIAlertAction(title:"Send Feedback", style:UIAlertActionStyle.Default, handler:{ action in
    self.presentFeedbackForm()
  }))
  settingsActionSheet.addAction(UIAlertAction(title:"Tell Me a Joke!", style:UIAlertActionStyle.Default, handler:{ action in
    self.presentRandomJoke()
  }))
  settingsActionSheet.addAction(UIAlertAction(title:"Cancel", style:UIAlertActionStyle.Cancel, handler:nil))
  presentViewController(settingsActionSheet, animated:true, completion:nil)
}

Вот как это выглядит представлено:

AlertViewController в Swift

person Zorayr    schedule 28.04.2015

Обновлено для Swift 3:

Если вы хотите показать/открыть UIActionSheet при нажатии кнопки, используйте приведенный ниже простой и обновленный код в вашем ViewController:

//Определение метода:

func showPaymentModeActionSheet()  {

    // 1
    let optionMenu = UIAlertController(title: nil, message: "Choose Payment Mode", preferredStyle: .actionSheet)

    // 2
    let fullAction = UIAlertAction(title: "FULL", style: .default, handler: {
        (alert: UIAlertAction!) -> Void in
        self.mPaymentModeTextField.text = "FULL"

    })
    let addvanceAction = UIAlertAction(title: "ADVANCE", style: .default, handler: {
        (alert: UIAlertAction!) -> Void in
        self.mPaymentModeTextField.text = "ADVANCE"
    })

    //
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
        (alert: UIAlertAction!) -> Void in
    })


    // 4
    optionMenu.addAction(fullAction)
    optionMenu.addAction(addvanceAction)
    optionMenu.addAction(cancelAction)

    // 5
    self.present(optionMenu, animated: true, completion: nil)
}

//Вызов метода:

@IBAction func actionOnPaymentModeButton(_ sender: Any) {
    // open action sheet
    showPaymentModeActionSheet()
}
person Kiran Jadhav    schedule 22.08.2017

Показать лист действий в Swift 4/5

    @IBAction func showActionSheet(sender: AnyObject) {

    let alert = UIAlertController(title: "Title", message: "Please Select an Option", preferredStyle: .actionSheet)

    
    alert.addAction(UIAlertAction(title: "Edit", style: .default , handler:{ (UIAlertAction)in
        print("User click Edit button")
    }))

    alert.addAction(UIAlertAction(title: "Delete", style: .destructive , handler:{ (UIAlertAction)in
        print("User click Delete button")
    }))
    
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:{ (UIAlertAction)in
        print("User click Dismiss button")
    }))


    self.present(alert, animated: true, completion: {
        print("completion block")
    })
}

введите здесь описание изображения

person Solayman Rana    schedule 10.01.2021