Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the index of item selected in Alert of UIAlertController Swift

I am going to use UIAlertController for a user to select one item. The items to select are array as following:

let arraySelect = ["NewYork", "Washington", "Seoul", "Tokyo", "Peking", "Sidney", ... ]

   let alert = UIAlertController(title: nil, message: nil, preferredStyle: .Alert)

        // Add items in array to Alert
        for var i = 0; i < arraySelect.count; i++ {
            alert.addAction(UIAlertAction(title: arrayBibleVersions[i], style: .Default, handler: {(_) in }))
        }

        // Add cancel button.    
        alert.addAction(UIAlertAction(title: "취소", style: .Cancel, handler: {(_) in }))

        self.presentViewController(alert, animated: false, completion: nil)

When a user touched one item, I have to get the index of the item that a user toched on. But I don't know how to get the index.. Please help me.

like image 356
user3615509 Avatar asked Dec 24 '22 12:12

user3615509


1 Answers

I solved my question as following:

    let arraySelect = ["NewYork", "Washington", "Seoul", "Tokyo", "Peking", "Sidney", ... ]

    let alert = UIAlertController(title: nil, message: nil, preferredStyle: .Alert)

    let closure = { (action: UIAlertAction!) -> Void in
        let index = alert.actions.indexOf(action)

        if index != nil {
            NSLog("Index: \(index!)")
        }
    }

    for var i = 0; i < arrayBibleVersions.count; i++ {
        alert.addAction(UIAlertAction(title: arrayBibleVersions[i][1], style: .Default, handler: closure))
    }

    alert.addAction(UIAlertAction(title: "cancel", style: .Cancel, handler: {(_) in }))

    self.presentViewController(alert, animated: false, completion: nil)
like image 140
user3615509 Avatar answered Apr 27 '23 08:04

user3615509