在集合视图中选择单元格到新控制器

时间:2019-02-16 18:57:32

标签: ios swift cell collectionview

对代码编程和编程项目来说是新手。我已经设置了所有收藏夹视图,但是我无法弄清楚如何告诉特定的单元格导航到新的收藏夹视图或详细信息视图。非常困惑和沮丧。任何人都可以帮助我,或者至少可以指出正确的方向。请把它哑巴哈哈。

这是我的主要View控制器

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")


}

}

这是我收藏视图中的快捷文件

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]))

}



}

在第三个文件中,我只有这段代码

import UIKit

    class Legend: NSObject {

    var thumbnailImageName: String?

}

主视图控制器的底部代码确实打印出了一个“选定的”,但是它为每个单元格打印了它……我假设每个单元格都需要自己的viewController.swift文件?然后告诉该单元格到那个快速文件以显示内容?谢谢您的时间。

2 个答案:

答案 0 :(得分:0)

否,您不需要为每个单元格创建自己的struct Root: Decodable { let catID, catName, catParentid, name, year: String? private enum CodingKeys: String, CodingKey { case catID = "cat_id" case catName = "cat_name" case catParentid = "cat_parentid" case name, year } } 文件。您只需要创建一个详细信息页面屏幕(一个DetailViewController.swift),并使用在详细信息视图控制器上声明的变量传递所选单元格的详细信息即可。

就像我在演示项目中用您的代码完成了HERE一样,结果将是:

enter image description here

我所做的是我在情节提要中添加了detailViewController并还添加了类文件。并且func parseJSON() { let url = URL(string: "https://...") let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in guard error == nil else { print("returning error") return } guard let content = data else { print("not returning data") return } guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any] else { print("Error") return } do { let content = json["data"] as! [[String:String]] let staData = try JSONSerialization.data(withJSONObject:content,options:[]) self.tableArray = try JSONDecoder().decode([Root].self, from:staData) } catch { print(error) } print(self.tableArray) DispatchQueue.main.async { self.tableView.reloadData() } } task.resume() } 如下所示:

viewController.swift

在这里您可以使用didSelectItemAt传递数据(在这里我要传递选择的索引),因为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) } controller.selectedIndex = indexPath.row的属性,因为我已经在selectedIndex中声明了它,例如< / p>

DetailViewController

同样,您也可以传递与所选索引相关的其他数据。

有关更多信息,请参阅演示项目。

答案 1 :(得分:0)

如果要检查按了什么。您可以检查按什么类型的单元格:

if let cell = tableView.cellForRow(at: indexPath) as? VideoCell {
//check some property and go to new UIViewController or UICollectionViewController
//and transfer data 
}