Search code examples
iosxcodeswiftuiactionsheet

Swift - UIActionSheet events does not work


I'm trying to add actions/events to my action sheet, but when the buttons are pressed, nothing happens. My code looks like this:

@IBAction func sendTapped() {

    var sheet: UIActionSheet = UIActionSheet()
    let title: String = "Choose item to send:"
    sheet.title  = title
    sheet.addButtonWithTitle("Cancel")
    sheet.addButtonWithTitle("Text")
    sheet.addButtonWithTitle("Image")
    sheet.cancelButtonIndex = 0
    sheet.delegate = self
    sheet.tag = 1
    sheet.showInView(self.view)

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

        case 1:
            println("1 pressed")

        case 2:
            println("2 pressed")
        default:
            println("Nothing pressed")
        }
    }

}

Honestly I do not know why this wouldn't work. Please help me solve this problem.

Any suggestions would be appreciated.


Solution

  • Frank. You have the right idea. Your calling the clicked button index against the sheet tag. Instead call it against the button itself :

    func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
    switch buttonIndex {
        case 0: // your cancel button 
    Etc
    }
    }
    

    Additionally, if your coding for iOS8 it has been deprecated for UIAlertController which contains handlers. A lot easier. Just FYI. But if you are making it backwards compatible it doesn't work with iOS7.

    Additionally make sure your setting your delegate