使用动态项获取UIAlertAction的选择索引

bas*_*han 2 ios swift uialertcontroller uialertaction

我正在构建一个动态的动作列表.按动作时,我想跳到表格视图中的一个部分.为此,我想知道所选的操作索引并将其替换为代码部分:"inSection:0".这样做的方式?

这是我的代码:

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)
Run Code Online (Sandbox Code Playgroud)

luk*_*302 6

您可能希望使用以下enumerate基于循环的循环:

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)
}
Run Code Online (Sandbox Code Playgroud)