Swift: collectionviewHeader delegate not working?

。_饼干妹妹 提交于 2019-12-12 03:44:52

问题


Ok, Im still new with protocols but I need to call a function (that I know works when called in the header class) from another class.

To do this, In the class from which Im calling the function (its a MSMessagesAppViewController) I have:

public protocol MSMessagesAppViewControllerDelegate: class {
    func shrinkHeight(height:CGFloat)
    func growHeight(height: CGFloat)
}

weak var delegate: MSMessagesAppViewControllerDelegate?
delegate?.shrinkHeight(height: 90)

Then I have in class HeaderCollectionReusableView: UICollectionReusableView, MSMessagesAppViewControllerDelegate the actual functions:

 func shrinkHeight(height:CGFloat)
    {
        print("WORKING!!");  //NOT printed

        UIView.animate(withDuration: 0.7, delay: 0.0, usingSpringWithDamping:
            0.6, initialSpringVelocity: 1.1, options: [], animations: {
                //thing being animated

                self.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.screenSize.height * (height/self.screenSize.height))

                //change out
                    self.squareLogo.isHidden = true
                    self.logoLabel.isHidden = false
        }, completion: { finished in
            //code that runs after the transition is complete here


        })
    }

    func growHeight(height:CGFloat)
    {

It compiles but I know the functions above aren't called because no print statement. What am I doing wrong here?


回答1:


I had the same issue few seconds ago. I think you have the same problem as I had.

In you custom UICollectionView class where you implemented MSMessagesAppViewControllerDelegate you have to add the delegate for the reusable cell.

Something like that:

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    if kind == UICollectionElementKindSectionHeader {
        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerCell", for: indexPath) as! YourCustomClassForHeader
        headerView.delegate = self // here was my problem, I just forgot to set the delegate
        return headerView
    } else {
        return UICollectionReusableView()
    }
}


来源:https://stackoverflow.com/questions/41785435/swift-collectionviewheader-delegate-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!