Search code examples
iosswiftcellcollectionview

Choose cell in collection view to new controller


Very new to code and making a project programmatically. I have my collection view all set up but i cant figure out how to tell a specific cell to navigate to a new collection view or detail view. Very confused and frustrated. can anyone help me or at least point me in the right direction. please dumb it down haha.

this is my main View controller

import UIKit



class HomeController: UICollectionViewController, 
UICollectionViewDelegateFlowLayout {


    var Legends: [Legend] = {
    var select1 = Legend()
    select1.thumbnailImageName = "select1thumbnail"
    var select2 = Legend()
    select2.thumbnailImageName = "select2humbnail"

    return[select1, select2]        
}()

    override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.title = "Choose Selection"
    collectionView.backgroundView = UIImageView(image: UIImage(named: "backgroundlogo"))
    collectionView?.register(VideoCell.self, forCellWithReuseIdentifier: "cellId")
    collectionView.dataSource = self
    collectionView.delegate = self



    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return Legends.count

}
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! VideoCell

    cell.legend = Legends[indexPath.item]       
    return cell

}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width:view.frame.height, height: 150)
    }

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0

}

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let select2VC = UIViewController()
    navigationController?.navigationBar.tintColor = UIColor.white
    navigationController?.pushViewController(select2VC, animated: true)

 print("selcected")


}

}

this is the swift file i have for my collection view

import UIKit



class VideoCell: UICollectionViewCell {

var legend: Legend? {
    didSet {
        thumbnailImageView.image = UIImage(named: (legend?.thumbnailImageName)!)

    }
}

override init(frame: CGRect) {
    super.init(frame: frame)
    setupViews()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

let thumbnailImageView: UIImageView = {
    let imageView = UIImageView()
    imageView.backgroundColor = UIColor.darkGray
    imageView.image = UIImage(named:"bgcolor")
    imageView.contentMode = .scaleAspectFit
    imageView.clipsToBounds = true
    imageView.translatesAutoresizingMaskIntoConstraints = false
    return imageView
}()

func setupViews() {
    addSubview(thumbnailImageView)

    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-16-[v0]-16-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["v0": thumbnailImageView]))
    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-1-[v0]-0-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["v0": thumbnailImageView]))

}



}

in a 3rd file i have just this bit of code

import UIKit

    class Legend: NSObject {

    var thumbnailImageName: String?

}

the bottom code of the main view controller does print out a "selected" but it prints it for every cell... I assume each cell will need its own viewController.swift file? then tell that cell to that swift file to show the contents?? thank you for your time.


Solution

  • No you don't need to create its own viewController.swift file for each cell. You just need to create one detail page screen (one DetailViewController.swift) and you need to pass the detail of selected cell with variables declared on detail view controller.

    Like I have done HERE in demo project with your code and result will be:

    enter image description here

    What I have done is I have added detailViewController in storyboard and also added class file. and didSelectItemAt will look like:

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
        controller.selectedIndex = indexPath.row //pass selected cell index to next view.
        self.navigationController?.pushViewController(controller, animated: true)
    
    }
    

    Here you can pass data with controller.selectedIndex = indexPath.row (Herer I am passing selected index) because selectedIndex is a property of DetailViewController because I have declared it in DetailViewController.swift like

    var selectedIndex = 0
    

    And same way you can pass other data as well which is related with selected index.

    For more info refer demo project.