使用动态项

时间:2016-01-23 15:34:52

标签: 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)

1 个答案:

答案 0 :(得分: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)
}