Maric Vikike
Maric Vikike

Reputation: 247

How to trigger an function of an UICollectionViewCell inside an UICollectionViewController?

I would like to trigger the animation3() function (which is a function inside PageCell() which is a UICollectionViewCell) inside the BreathingSwpipingController which is a UICollectionViewController.

class BreathingSwipingController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

var pageCell: PageCell?

override func viewDidLoad() {

    super.viewDidLoad()

    collectionView.backgroundColor = .white
    collectionView.register(PageCell.self, forCellWithReuseIdentifier: "cellId")
    collectionView.isPagingEnabled = true

    setupStartStopButton()

}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 3
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    pageCell = (collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as? PageCell)!
    return pageCell!
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectionView.frame.width, height: collectionView.frame.height)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

@objc func startStopTapped() {

        pageCell!.animation3()

}

}

Upvotes: 0

Views: 88

Answers (1)

user9204495
user9204495

Reputation:

Make PageCell a delegate of BreathingSwipingController by making a protocol

protocol BreathingSwipingDelegate: class {
 func doSth()
}

now inside UICollectionViewController define a weak var delegate: BreathingSwipingDelegate?

then head to PageCell file and conform to that protocol

class PageCell:  BreathingSwipingDelegate .... {

func doSth() {
animation3()

}
var mController = BreathingSwipingController()
override init(style: .....) { 
mController.delegate = self
.
.
.
.
}
}

now in BreathingSwipingController make the following

@objc func startStopTapped() {

        delegate?.doSth()
}

Upvotes: 1

Related Questions