bashan
bashan

Reputation: 3602

Get select index of UIAlertAction with dynamic items

I am building a dynamic list of actions. When pressing an action I would like to jump to a section in a table view. For this I would like to know the selected index of the action and replace it on the code section: "inSection: 0". Any way of doing it?

Here is my code:

let optionMenu = UIAlertController(title: nil, message: "Jump to", preferredStyle: .ActionSheet)

for item in items {
    let action = UIAlertAction(title: item, style: .Default, handler: { (alert: UIAlertAction!) -> Void in
        let indexPath = NSIndexPath(forRow: 0, inSection: 0)
        self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)
    })
    optionMenu.addAction(action)
}

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

Upvotes: 3

Views: 1691

Answers (1)

luk2302
luk2302

Reputation: 57164

You might want to use the following enumerate-based loop instead:

for (index, item) in items.enumerate() {
    let action = UIAlertAction(title: item, style: .Default, handler: { (alert: UIAlertAction!) -> Void in        
        let indexPath = NSIndexPath(forRow: 0, inSection: index) // <- index
        self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)
    })
    optionMenu.addAction(action)
}

Upvotes: 7

Related Questions