如何为UICollectionView的每个单元格执行segue到不同的View Controller

时间:2016-05-25 23:05:51

标签: xcode uicollectionview xcode7 segue uicollectionviewcell

以下是我的ViewController.swift

的代码

我有一个带4个单元格的UICollectionView。我希望每个单元格都可以切换到不同的View Controller。有人能指出我正确的方向吗?

我的故事板上每个segues的标识符都是“showImage”和“showImage2”。

import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource
{

    @IBOutlet weak var collectionView: UICollectionView!

    let otm_HomePage = ["Philosophy", "Polos", "Sweaters", "Gallery"]

    let imageArray = [UIImage(named: "otm_Logo"), UIImage(named: "royal1"), UIImage(named: "Sweater"), UIImage(named: "Webpic")]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.otm_HomePage.count
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        //creating cell object for each ittem in array
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath)
            as! CollectionViewCell
        //make image of cell image in array
        cell.imageView?.image = self.imageArray[indexPath.row]
        //make title of cell title in array
        cell.titleLabel?.text = self.otm_HomePage[indexPath.row]
        return cell

    }


    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        self.performSegueWithIdentifier("showImage", sender: self)

    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "showImage"
        {
            let indexPaths = self.collectionView!.indexPathsForSelectedItems()!
            let indexPath = indexPaths[0] as NSIndexPath

            let vc = segue.destinationViewController as! NewViewController


            vc.image = self.imageArray[indexPath.row]!
            vc.title = self.otm_HomePage[indexPath.row]
        }
        if segue.identifier == "showImage2"{

        }
    }

}

0 个答案:

没有答案