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

How to navigate another view controller when clicking on item inside cell of collectionView Using Swift 3

我们希望通过在 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!)
    }  
}

主要问题

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

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

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

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

提前致谢

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

此代码:

var homeViewcontroller = HomeViewController()

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

老实说,您链接所有内容的方式很奇怪,而且不是很直观。但是如果你想在不改变你的代码太多的情况下解决你的问题,你必须向下传递 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 本身。但是,如果您决定这样做,请确保将其作为带有 "weak" 属性 的 "optional" 变量传递,否则您将创建一个保留循环。

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

首先在您的单元格中创建一个枚举 class 并根据您的图像视图命名案例,以便您的控制器知道单击了哪个图像视图并且您也可以 link 您的标签.类似于:

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

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

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

然后在您的单元格中创建一个弱变量 class 并在您的操作处理程序方法中调用协议方法

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

然后在您的视图控制器中 class 您是否必须确认 HomeMainCatgCellDelegate 协议并将单元格的委托设置为自身。

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
          }
    }
}
}

希望这对您有所帮助。