![](/img/trans.png)
[英]Swift 2.1 - How to pass index row of collection view cell to another view controller
[英]Swift 2.1 - How to pass index path row of collectionView cell to segue
從集成了集合視圖的主控制器中,我想將選定的單元格索引路徑傳遞給另一個視圖控制器(詳細信息視圖),以便可以使用它來更新特定的記錄。
我有以下工作prepareForSegue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "RecipeDetailVC" {
let detailVC = segue.destinationViewController as? RecipeDetailVC
if let recipeCell = sender as? Recipe {
detailVC!.recipe = recipeCell
}
}
}
而且我嘗試過let indexPath = collection.indexPathForCell(sender as! UICollectionViewCell)
包含在內,但是在運行時我Could not cast value of type 'xxx.Recipe' (0x7fae7580c950) to 'UICollectionViewCell'
。
我也有performSegueWithIdentifier("RecipeDetailVC", sender: recipeCell)
,我想知道是否可以使用它傳遞所選單元格的索引路徑,但不確定是否可以將此索引添加到發送者。
我不清楚您的collectionViewCell的層次結構。 但我認為sender
可能不是牢房。 嘗試使用
let indexPath = collection.indexPathForCell(sender.superView as! UICollectionViewCell)
要么
let indexPath = collection.indexPathForCell(sender.superView!.superView as! UICollectionViewCell)
那可能行得通。
我已經寫了一個簡單的示例向您展示,它使用tableView但概念是相同的:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var things = [1,2,3,4,5,6,7,8] // These can be anything...
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let objectForCell = self.things[indexPath.row] // Regular stuff
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let objectAtIndex = self.things[indexPath.row]
let indexOfObject = indexPath.row
self.performSegueWithIdentifier("next", sender: indexOfObject)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "next" {
// On this View Controller make an Index property, like var index
let nextVC = segue.destinationViewController as! UIViewController
nextVC.index = sender as! Int
}
}
}
在這里,您可以看到獲得了實際的對象本身,並將其用作perform segue方法中的發送者。 您可以在prepareForSegue中訪問它,並將其直接分配給目標視圖控制器上的屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.