简体   繁体   English

将数据从 CollectionVewCell 传递到另一个视图 controller

[英]Passing data from CollectionVewCell to another view controller

Let's say we have CollectionViewController with Cells So, my goal is to send the data from the active CollectionViewControllerCell (let's say i want to pass the category name) to another controller after click action on that CELL.假设我们有带有 Cells 的 CollectionViewController 因此,我的目标是在单击该 CELL 后将数据从活动的 CollectionViewControllerCell(假设我想传递类别名称)发送到另一个 controller。 So, how can i pass data from那么,我如何从

import UIKit

class CategoriesViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!
    
    var activeCategoryItemTitle:String = ""
    var categories = Category.fetchCategories()
    let cellScale: CGFloat = 0.7
        
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let screenSize = UIScreen.main.bounds.size
        let cellWidth =  floor(screenSize.width * cellScale)
        let cellHeight = floor(screenSize.height * cellScale)
        let insetX  = (view.bounds.width - cellWidth) / 2
        let insetY  = (view.bounds.height - cellHeight) / 2
        let layout = collectionView!.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width:cellWidth,height:cellHeight)

    //  collectionView.contentInset = UIEdgeInsets(top:insetY,left:insetX,bottom:insetY,right:insetX)
        print(insetY)
        
        collectionView.dataSource = self
        collectionView.delegate = self
    }
   
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let destinationVC: ProductsViewController = segue.destination as! ProductsViewController
        destinationVC.titleOfCategory = self.activeCategoryItemTitle
    //  let product = ProductsViewController()
    //  product.titleOfCategory = "asd"
    }
}

// MARK UICollectionViewDataSource

extension CategoriesViewController:
    UICollectionViewDataSource
{
    
    func numberOfSections(in collectionView: UICollectionView) ->
        Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
        return categories.count
    }
    
    func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell =
            collectionView.dequeueReusableCell(withReuseIdentifier: "CategoriesCollectionViewCell",for:indexPath) as!
        CategoriesCollectionViewCell
        let category = categories[indexPath.item]
        cell.category = category

        return cell
    }
}

extension CategoriesViewController: UIScrollViewDelegate, UICollectionViewDelegate
{
    
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        let layout = self.collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
        
        let cellWidthincludingSpacing = layout.itemSize.width+layout.minimumLineSpacing
        
        var offset = targetContentOffset.pointee
        
        let index = (offset.x + scrollView.contentInset.left) / cellWidthincludingSpacing
        
        let roundedIndex = round(index)
        
        offset = CGPoint(x: roundedIndex*cellWidthincludingSpacing-scrollView.contentInset.left, y: scrollView.contentInset.top)
        
        targetContentOffset.pointee = offset
       
    }
}

and second one is my products list controller, that must receive category name and put inside view第二个是我的产品列表 controller,必须接收类别名称并放入视图

//
import UIKit

class ProductsViewController: UIViewController {

    @IBOutlet weak var categoryTitle: UILabel!
    var titleOfCategory:String = ""
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    var products = Product.fetchProducts()
//  let cellScale: CGFloat = 0.63
        
    override func viewDidLoad() {
        super.viewDidLoad()
        categoryTitle.text = titleOfCategory
//      let screenSize = UIScreen.main.bounds.size
//      let cellWidth =  floor(screenSize.width * cellScale)
//      let cellHeight = floor(screenSize.height * cellScale)
//      let insetX  = (view.bounds.width - cellWidth) / 2
//      let insetY  = (view.bounds.height - cellHeight) / 2
//      let layout = collectionView!.collectionViewLayout as! UICollectionViewFlowLayout
//      layout.itemSize = CGSize(width:cellWidth,height:cellHeight)
//      collectionView.contentInset = UIEdgeInsets(top:insetY,left:insetX,bottom:insetY,right:insetX)
//      collectionView.dataSource = self
//      collectionView.delegate = self
    }
}

// MARK UICollectionViewDataSource
extension ProductsViewController:
    UICollectionViewDataSource
{
    func numberOfSections(in collectionView: UICollectionView) ->
        Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
        return products.count
    }
    
    func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell =
            collectionView.dequeueReusableCell(withReuseIdentifier: "ProductsCollectionViewCell",for:indexPath) as!
        ProductsCollectionViewCell
        
        let product = products[indexPath.item]
        
        cell.product = product
        
        return cell
    }
}

extension ProductsViewController: UIScrollViewDelegate, UICollectionViewDelegate
{
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        let layout = self.collectionView?.collectionViewLayout as! UICollectionViewFlowLayout
        
        let cellWidthincludingSpacing = layout.itemSize.width+layout.minimumLineSpacing
        
        var offset = targetContentOffset.pointee
        
        let index = (offset.x + scrollView.contentInset.left) / cellWidthincludingSpacing
        
        let roundedIndex = round(index)
        
        offset = CGPoint(x: roundedIndex*cellWidthincludingSpacing-scrollView.contentInset.left, y: scrollView.contentInset.top)
        
        targetContentOffset.pointee = offset
        
    }
}

1, add didSelectItemAt to your collectionView, this will handle the click on the cell. 1,将didSelectItemAt添加到你的collectionView,这将处理单元格上的点击。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    performSegue(withIdentifier: "showProducts", sender: categories[indexPath.item])

}

2, In your CategoriesViewController start type "prepare" and you will see the prepare for segue method. 2,在您的 CategoriesViewController 开始输入“prepare”,您将看到 prepare for segue 方法。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showProducts" {
            let destination = segue.destination as! ProductsViewController
            destination.titleOfCategory = sender as? String
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM