将数据从CollectionVewCell传递到另一个视图控制器

时间:2020-08-17 07:35:57

标签: swift iphone xcode delegates segue

假设我们有带有单元格的CollectionViewController 因此,我的目标是在对该CELL进行单击操作之后,将数据从活动的CollectionViewControllerCell(假设我要传递类别名称)发送到另一个控制器。因此,我该如何传递来自

的数据
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
       
    }
}

第二个是我的产品列表控制器,该控制器必须接收类别名称并放在视图中

//
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 个答案:

答案 0 :(得分:0)

1,将didSelectItemAt添加到您的collectionView中,这将处理对单元格的单击。

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

}

2,在CategoriesViewController中,开始输入“ prepare”,您将看到“准备segue”方法。

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