简体   繁体   English

CollectionView 单元格委托 swift

[英]CollectionView cell delegate swift

I have ViewController with collectionView and UICollectionViewDataSource extension:我有带有 collectionView 和 UICollectionViewDataSource 扩展的 ViewController:

 class CheckInViewController: UIViewController {
    let checkInSystem = CheckInSystem()
    let collectionView = UICollectionView()
    
viewDidAppear(){
 super.viewDidAppear(animated)
 checkInSystem.lala() // its function which should call delegate
}


    //...

}

extension CheckInViewController: UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CheckInCell.identifier, for: indexPath) as! CheckInCell

    }

Also there are protocol:还有协议:

protocol AnimateTheLastCheckInDayDelegate: AnyObject{
    func animateLastDay(_ cell: CheckInCell)
}

And it's realisation这是实现

extension CheckInViewController: AnimateTheLastCheckInDayDelegate{
    func animateLastDay(_ cell: CheckInCell) {
        cell.backgroundColor = .red
        print(1233254234) //works
    }
class CheckInSystem{
    weak var animateTheLastCheckInDayDelegate: AnimateTheLastCheckInDayDelegate?
    func checkInScreenLaunched(){
//...
 func lala(){
    animateTheLastCheckInDay?.animateLastDay(CheckInCell()) 

 }
}

I need to change cell background from animateTheLastCheckInDay?.animateLastDay(CheckInCell()) .我需要从animateTheLastCheckInDay?.animateLastDay(CheckInCell())更改单元格背景。 But It creates new cell.但它创造了新的细胞。 How to fix??怎么修??

This creates a new cell CheckInCell()这将创建一个新的单元格CheckInCell()

animateTheLastCheckInDay?.animateLastDay(CheckInCell()) 

You need to pass the cell so add implementation for delegate method willDisplay您需要传递单元格,因此为委托方法willDisplay添加实现

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell,  forItemAt indexPath: IndexPath)  {
    checkInSystem.lala(cell)
} 

With

func lala(_ cell: CheckInCell)
  animateTheLastCheckInDay?.animateLastDay(cell)  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM