timpone timpone - 1 year ago 114
Swift Question

overriding a method in UICollectionViewLayout in Swift with an error

I need to make a change to an app that we are developing and am not a full-time iOS dev. I'm trying to get a pinterest like interface for an iOS app and am working through the tutorial here: https://www.raywenderlich.com/107439/uicollectionview-custom-layout-tutorial-pinterest

In their custom UICollectionViewLayout, they override

but I'm getting an error from the XCode 8 compiler (although running with Use Legacy Swift Language Version set to Yes).

The error I get is:
Method does not override any method from its superclass

The abbreviated code is:

class PinterestLayout: UICollectionViewLayout {

override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {

var layoutAttributes = [UICollectionViewLayoutAttributes]()

// Loop through the cache and look for items in the rect
for attributes in cache {
if CGRectIntersectsRect(attributes.frame, rect ) {
return layoutAttributes

If I switch the method to private it compiles but doesn't work and if I remove the override, it gives me a conflict. I do want to override the underlying method but am not sure how to get this to work.

Answer Source

You have the wrong method signature. This is actually the reason the override keyword exists. It ensures an API change will be caught like this, rather than the override silently not occurring, leading to hard to diagnose issues.

It should be

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]?
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download