iosxcodeswift3uicollectionviewdelegate

Swift 3 Warning in UICollectionViewDelegate


I am using Xcode 8 and Swift 3. I was designing the UICollectionView and wanted to set height and width dynamically so wanted for some answers. On the way I got this solution(Correct or not - I have No Idea):

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

    let Labell : UILabel = UILabel()
    Labell.text =   self.items[indexPath.item]
    let labelTextWidth =   Labell.intrinsicContentSize.width
    return CGSize(width: labelTextWidth + 20, height: 35)

}

But this answer was in swift 2.0 And person who gave this answer claims that it is solved one. I pasted it in Xcode and changed some thing that Xcode suggested me.

Now here I am getting following warning:

instance method 'collectionView:layout:sizeForItemAtIndexPath:)' nearly matches optional requirement 'collection(_:willDisplaySupplementaryView:forElement:at:)' of protocol 'UICollectionViewDelegate'

Xcode suggests me 2 solutions 1) add private ahead of func keyword 2) add @nonobjc in front of fun keyword

I tried both solutions and it suppresses the warning but none the above is never called. I tried putting break point and tried many ways. If anyone can pull me out of this pit.


Solution

  • There is no sizeForItemAtIndexPath delegate method for UICollectionViewDelegate.

    What you're probably looking for is

    optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    

    which can be found on the UICollectionViewDelegateFlowLayout protocol.

    Try replacing your code with this:

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    
        let Labell : UILabel = UILabel()
        Labell.text =   self.items[indexPath.item]
        let labelTextWidth =   Labell.intrinsicContentSize.width
        return CGSize(width: labelTextWidth + 20, height: 35)
    
    }