使用Swift 3单击collectionView单元格内的项目时如何导航另一个视图控制器

Posted

技术标签:

【中文标题】使用Swift 3单击collectionView单元格内的项目时如何导航另一个视图控制器【英文标题】:How to navigate another view controller when clicking on item inside cell of collectionView Using Swift 3 【发布时间】:2017-04-20 05:34:17 【问题描述】:

我们希望通过在单击cell collection 内的项目 (i.e ImageView) 时替换主控制器来显示另一个控制器。但是我们无法获得主集合视图,也无法导航目标控制器。我们正在使用以下方法 -

HomeViewComtroller.swift

import LBTAComponents

class HomeViewController: DatasourceController 

    override func viewDidLoad() 
        super.viewDidLoad()
        navigationItem.title = "Home"
        collectionView?.contentInset = UIEdgeInsetsMake(50, 0, 0, 0)
        collectionView?.scrollIndicatorInsets = UIEdgeInsetsMake(50, 0, 0, 0)
        collectionView?.backgroundColor = UIColor(r: 232, g: 236, b: 241, a: 1)
        let homeViewDatasource = HomeViewDatasource()
        self.datasource = homeViewDatasource
    


    override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 

        if indexPath.section == 0 
            return CGSize(width: view.frame.width, height: 120)
         else if indexPath.section == 6 
            return CGSize(width: view.frame.width, height: 120)
         else 
             return CGSize(width: view.frame.width, height: 200)
            


    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize 
            return CGSize(width: view.frame.width, height: 33)
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize 
        return CGSize(width: view.frame.width, height: 10)
    


//    lazy var homeMainCatgCell: HomeMainCatgCell = 
//        let homemain = HomeMainCatgCell ()
//        homemain.homeViewcontroller = self
//        return homemain
//    ()


    func handleCtgClick (ctgname: String ,ctgId: String) 

        let dummySettingViewController = UIViewController()
        dummySettingViewController.view.backgroundColor = UIColor.white
        dummySettingViewController.navigationItem.title = ctgname
        navigationController?.navigationBar.tintColor = UIColor.white
        navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
        navigationController?.pushViewController(dummySettingViewController, animated: true)

    


HomeViewDatasource

import LBTAComponents

class HomeViewDatasource: Datasource 

    override func headerClasses() -> [DatasourceCell.Type]? 
         return [HomeMainCatgCellHeader.self,HomeSaleCatgCellHeader.self,HomeNewArrivalCellHeader.self,HomeBestSallingCellHeader.self,HomeBigDiscountCellHeader.self,HomeSpecialOfferCellHeader.self,HomeBrandCellHeader.self]
    
    override func footerClasses() -> [DatasourceCell.Type]? 
        return[HomeCellsFooter.self]
    
    override func cellClasses() -> [DatasourceCell.Type] 
        return [HomeMainCatgCell.self,HomeSaleCtagCell.self,HomeNewArrivalsCell.self,HomeBestSallingCatgCell.self,HomeBigDiscountCatgCell.self,HomeSpecialOfferCatgCell.self,HomeBrandVIewCell.self]
    
    override func numberOfItems(_ section: Int) -> Int 
        return 1
    
    override func numberOfSections() -> Int 
        return 7
    

HomeMainCatgCell.swift

import LBTAComponents

class HomeMainCatgCell: DatasourceCell 
    var homeViewcontroller: HomeViewController?
    let personalcareCatgImageView: UIImageView = 
        let iv = UIImageView()
        iv.image = #imageLiteral(resourceName: "personalcareimage")
        iv.tag = 0
        iv.contentMode = .scaleToFill
        return iv
    ()

    let healthcareCatgImageView: UIImageView = 
        let iv = UIImageView()
        iv.image = #imageLiteral(resourceName: "healthcareimage")
        iv.contentMode = .scaleToFill
        iv.tag = 1
        return iv
    ()

    let homecareCatgImageView: UIImageView = 
        let iv = UIImageView()
        iv.image = #imageLiteral(resourceName: "homecareimage")
        iv.contentMode = .scaleToFill
        iv.tag = 2
        return iv
    ()

    let kitchencareCatgImageView: UIImageView = 
        let iv = UIImageView()
        iv.image = #imageLiteral(resourceName: "kitchencareiamge")
        iv.contentMode = .scaleToFill
        iv.tag = 3
        return iv
    ()


    override func setupViews() 
        super.setupViews()
        let personalcareCatgImageContainerView = UIView()
        personalcareCatgImageContainerView.backgroundColor = .white

        let homecareCatgImageContainerView = UIView()
        homecareCatgImageContainerView.backgroundColor = .white


        let healthcareCatgImageContainerView = UIView()
        healthcareCatgImageContainerView.backgroundColor = .white


        let kitchencareCatgImageContainerView = UIView()
        kitchencareCatgImageContainerView.backgroundColor = .white


        let imageStackView = UIStackView(arrangedSubviews: [personalcareCatgImageContainerView,homecareCatgImageContainerView,healthcareCatgImageContainerView,kitchencareCatgImageContainerView])
        imageStackView.axis = .horizontal
        imageStackView.distribution = .fillEqually
        addSubview(imageStackView)
        imageStackView.anchor(topAnchor, left: leftAnchor, bottom: self.bottomAnchor, right: self.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: frame.width, heightConstant: frame.height)

        imageStackView.addSubview(personalcareCatgImageView)
        imageStackView.addSubview(healthcareCatgImageView)
        imageStackView.addSubview(homecareCatgImageView)
        imageStackView.addSubview(kitchencareCatgImageView)

        personalcareCatgImageView.anchor(personalcareCatgImageContainerView.topAnchor, left: personalcareCatgImageContainerView.leftAnchor, bottom: personalcareCatgImageContainerView.bottomAnchor, right: personalcareCatgImageContainerView.rightAnchor, topConstant: 5, leftConstant: 5, bottomConstant: 5, rightConstant: 5, widthConstant: personalcareCatgImageContainerView.frame.width , heightConstant: personalcareCatgImageContainerView.frame.width)

          healthcareCatgImageView.anchor(healthcareCatgImageContainerView.topAnchor, left: healthcareCatgImageContainerView.leftAnchor, bottom: healthcareCatgImageContainerView.bottomAnchor, right: healthcareCatgImageContainerView.rightAnchor, topConstant: 5, leftConstant: 5, bottomConstant: 5, rightConstant: 5, widthConstant: healthcareCatgImageContainerView.frame.width , heightConstant: healthcareCatgImageContainerView.frame.width)

          homecareCatgImageView.anchor(homecareCatgImageContainerView.topAnchor, left: homecareCatgImageContainerView.leftAnchor, bottom: homecareCatgImageContainerView.bottomAnchor, right: homecareCatgImageContainerView.rightAnchor, topConstant: 5, leftConstant: 5, bottomConstant: 5, rightConstant: 5, widthConstant: homecareCatgImageContainerView.frame.width , heightConstant: homecareCatgImageContainerView.frame.width)

          kitchencareCatgImageView.anchor(kitchencareCatgImageContainerView.topAnchor, left: kitchencareCatgImageContainerView.leftAnchor, bottom: kitchencareCatgImageContainerView.bottomAnchor, right: kitchencareCatgImageContainerView.rightAnchor, topConstant: 5, leftConstant: 5, bottomConstant: 5, rightConstant: 5, widthConstant: kitchencareCatgImageContainerView.frame.width , heightConstant: kitchencareCatgImageContainerView.frame.width)

        personalcareCatgImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleClickCtg)))
        personalcareCatgImageView.isUserInteractionEnabled = true
        healthcareCatgImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleClickCtg)))
        healthcareCatgImageView.isUserInteractionEnabled = true
        homecareCatgImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleClickCtg)))
        homecareCatgImageView.isUserInteractionEnabled = true
        kitchencareCatgImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleClickCtg)))
        kitchencareCatgImageView.isUserInteractionEnabled = true
    

    func handleClickCtg(gestureRecognizer: UITapGestureRecognizer) 
        var CtgName: String? = nil
        var CtgId: String? = nil
        guard let tag = gestureRecognizer.view?.tag else return
        print(tag)
        switch tag 
        case 0:
            CtgName = "Personal Care"
            CtgId = "121"
        case 1:
            CtgName = "Health Care"
            CtgId = "122"
        case 2:
            CtgName = "Home Care"
            CtgId = "123"
        case 3:
            CtgName = "Kitchen Care"
            CtgId = "124"
        default:
            return
        
        self.homeViewController?.handleCtgClick(ctgname: CtgName! ,ctgId: CtgId!)
      

主要问题

首先我没有绑定整个单元格的点击,我只想点击单元格内的 ImageView。因此,为此我将 GestureRecognizer 绑定在图像视图上,例如 -

kitchencareCatgImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleClickCtg)))

点击事件在通过print(tag) 内部点击功能打印标签(添加到图像视图)方面工作正常。但是当调用函数self.homeViewcontroller.handleCtgClick(ctgname: CtgName! ,ctgId: CtgId!)时(函数存在于HomeViewcontroller类中)。它不会改变视图控制器。

我还调试了handleCtgClick 函数,发现我得到HomeViewcontroller 的对象是nil

提前致谢

【问题讨论】:

您能否更具体地说明实际问题是什么?你得到什么错误?还是怎么了? (人们不应该通过你的代码来找出问题所在。你应该指出它。) 你能不能展示一下cellForItemAt方法。 确保 ViewController 嵌入在 UINavigationController 中。如果没有,它不会推送 ViewController。 @MacKa 它已嵌入 【参考方案1】:

如果您在单元类中声明控制器的全局实例,这将创建一个引用循环并在您的应用中创建一个泄漏。您的单元格将对您的控制器有一个强引用,并且您的控制器将对您的 tableview 有一个强引用,这反过来又保持对单元格的强引用,其次,如果您可能无法告诉单击的单元格的索引路径允许编辑。您可以尝试以下方法来克服这两个问题。

首先,在您的单元格类中创建一个枚举,其中包含根据您的图像视图命名的案例,以便您的控制器知道单击了哪个图像视图,并且您也可以将标签链接到它。比如:

enum CategoryViews:Int
    case personal = 0,healthcare = 1,homecare = 2,kitchencare = 3

然后在您的单元类中创建一个协议,例如:

protocol HomeMainCatgCellDelegate:class
   func clicked(view:CategoryViews,forCell cell:HomeMainCatgCell)

然后在你的单元格类中创建一个弱变量,并在你的动作处理方法中调用协议方法

class HomeMainCatgCell: DatasourceCell 
     weak var delegate:HomeMainCatgCellDelegate?
     //Remove the variable var homeViewcontroller: HomeViewController? to avoid reference cycle and we don't need it anyway.
 ...
func handleClickCtg(gestureRecognizer: UITapGestureRecognizer) 
    guard let tag = gestureRecognizer.view?.tag else return
    print(tag)
    if let clickedImageView = CategoryViews(rawValue:tag)
        self.delegate?.clicked(view:clickedImageView,forCell:self)
    
  

然后在您的视图控制器类中,您必须确认 HomeMainCatgCellDelegate 协议并将单元格的委托设置为 self。

class HomeViewController: DatasourceController, HomeMainCatgCellDelegate
...
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
//Dequeue your cell here
 cell.delegate = self
 ...
 return self

func clicked(view:CategoryViews,forCell cell:HomeMainCatgCell)
    //And you can handle your events accordingly here
    if let indexpath = self.collectionView.indexPath(for: cell)
    //Here you will get the indexpath of clicked cell and then you can put a switch condition to check which imageview is clicked
          switch view
          case .personal:break
          case .healthcare:break
          case .homecare:break
          case .kitchencare:break
          
    


希望这会有所帮助。

【讨论】:

如果我使用collectionView而不是imageViews,我需要更多帮助,那么我该怎么办...??任何想法 您可以查看此库以获取帮助github.com/DahanHu/DHCollectionTableView 是的,我已经这样做了,但同样的问题......不要导航到另一个 viewController【参考方案2】:

问题是您的“homeViewcontroller”变量设置不正确。

这段代码:

var homeViewcontroller = HomeViewController()

创建一个 HomeViewController 类的实例。但是这个实例与你认为的屏幕没有任何关系。呈现您当前视图的屏幕是一个完全不同的实例。

说实话,你链接所有东西的方式很奇怪,而且不是很直观。但是,如果您想在不过多更改代码的情况下解决问题,则必须向下传递 REAL HomeViewController。

所以在 HomeViewController.swift 你有这个代码:

let homeViewDatasource = HomeViewDatasource()
self.datasource = homeViewDatasource

将“handleCtgClick”作为闭包传递给它。

有点像

homeViewDataSource.presenterClosure = (ctgname: String ,ctgId: String) in 
        let dummySettingViewController = UIViewController()
        dummySettingViewController.view.backgroundColor = UIColor.white
        dummySettingViewController.navigationItem.title = ctgname
        navigationController?.navigationBar.tintColor = UIColor.white
        navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
        navigationController?.pushViewController(dummySettingViewController, animated: true)

(请注意,您必须在 HomeViewDatasource.swift 中创建此闭包变量声明,以便您可以从 HomeViewController.swift 分配它)

然后再次重复此步骤,将其传递给 HomeMainCatgCell.swift

然后您将能够引用您创建的局部闭包变量来调用此函数。

或者:

您可以将引用传递给 HomeViewController 本身。但是,如果您决定这样做,请确保将其作为具有“弱”属性的“可选”变量继续传递,否则您将创建一个保留循环。

【讨论】:

先生,您能给我举个例子吗?其实我没有正确理解你的意思。

以上是关于使用Swift 3单击collectionView单元格内的项目时如何导航另一个视图控制器的主要内容,如果未能解决你的问题,请参考以下文章

Swift-使用委托将数据附加到 CollectionView 中的 TableView

在 Swift 3 中使用 CGSize 的 collectionView 的 100% 宽度

Swift 3 - CollectionView 数据源未返回有效单元格

Swift 3 collectionView 如何设置间距。

使用 Swift 3 将 nib 加载到 collectionView 单元格中

SWIFT 3:将不同的声音文件数组匹配到 CollectionView 中的每个部分