2016-01-23 112 views
1

我正在構建動態動作列表。按下某個動作時,我想跳轉到表格視圖中的某個部分。爲此,我想知道所選操作的索引,並將其替換爲代碼部分:「inSection:0」。任何方式做到這一點?使用動態項目獲取UIAlertAction的選擇索引

這裏是我的代碼:

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) 

回答

4

您可能需要使用以下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) 
} 
+0

的偉大工程。謝謝! – bashan