Swift 2.1 - 如何将collectionView单元的索引路径行传递给segue

时间:2016-03-18 01:58:46

标签: ios swift

从我集成了集合视图的主控制器,我想将选定的单元索引路径传递给另一个视图控制器(详细视图) 所以我可以用它来更新特定的记录。

我有以下工作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),我想知道我是否可以使用它来传递所选单元格的索引路径,但不确定我是否可以将此索引添加到发件人。

2 个答案:

答案 0 :(得分:0)

我不清楚collectionViewCell的层次结构。但我认为sender可能不是一个细胞。尝试使用

let indexPath = collection.indexPathForCell(sender.superView as! UICollectionViewCell)

let indexPath = collection.indexPathForCell(sender.superView!.superView as! UICollectionViewCell)

这可能有用。

答案 1 :(得分:0)

我已经写了一个快速示例向您展示,它使用了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中访问它并将其直接分配给目标视图控制器上的属性。

相关问题