kiarash Teymourzadegan kiarash Teymourzadegan - 5 months ago 9
Swift Question

Pass my indexPath from collectionView witht two different cells for the the indexPath

I'm trying to pass my indexPath from collectionView in to my cell so that I could have two different cells for the the indexPath. I've tried passing instances of the controller and setting it to self in cell. I also tried protocol delegate and that didn't seem to work either. I use delegates quite often so I know I'm doing it right however, in this case my delegate function isn't even being called even tho I set the delegate to self in the Cell. I'm not sure what is happening but nothing seems to be working.

CollectionView VC

protocol ActivityAboutVCDelegtae: class {

func passIndexPath(indexPath:Int)
}

class ActivityAboutVC: UICollectionViewController, UICollectionViewDelegateFlowLayout {

var delegate:ActivityAboutVCDelegtae?

override func viewDidLoad() {
super.viewDidLoad()

self.collectionView!.registerClass(ActivityAboutCell.self, forCellWithReuseIdentifier: CELL_ID)
self.collectionView?.pagingEnabled = true
self.collectionView?.alwaysBounceVertical = false
}

// MARK: UICollectionViewDataSource
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

return 2
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CELL_ID, forIndexPath: indexPath) as! ActivityAboutCell

if delegate != nil {
delegate?.passIndexPath(indexPath.row)
}

return cell
}


CollectionViewCell

import UIKit

class ActivityAboutCell: BaseCell, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, ActivityAboutVCDelegtae {

lazy var actVc:ActivityAboutVC = {
let vc = ActivityAboutVC()
vc.delegate = self
return vc
}()


func passIndexPath(indexPath: Int) {
print(indexPath)
}

override func setupView() {
super.setupView()

ActivityAboutSetup()
backgroundColor = .whiteColor()
}

Answer

1) It is not clear what you want to achieve, but at lest the following solution will give you a way to call you passIndexPath method. Replace

if delegate != nil {
    delegate?.passIndexPath(indexPath.row)
}

with

cell.passIndexPath(indexPath.row)

2) UICollectionView uses items, not rows. This is why the final result should be

cell.passIndexPath(indexPath.item)

3) actVc property looks unnecessary or even wrong.

Comments