自定义 UICollectionViewLayout 的 layoutAttributesForElementsInRect 不会覆盖 Swift 2.0 中其超类的任何方法

Custom UICollectionViewLayout's layoutAttributesForElementsInRect does not override any method from its superclass in Swift 2.0

在将我的项目从 Swift 1.2 迁移到 2.0 时,我遇到了一个问题:我正在为我的 UICollectionView 使用自定义布局,它在 Swift 1.2 中运行良好。但是,在 Swift 2.0 中,当尝试覆盖自定义布局中的 layoutAttributesForElementsInRect 时会出现错误提示 Method does not override any method from its superclass

我试图删除 override,现在错误变成了 Method 'layoutAttributesForElementsInRect' with Objective-C selector 'layoutAttributesForElementsInRect:' conflicts with method 'layoutAttributesForElementsInRect' from superclass 'UICollectionViewLayout' with the same Objective-C selector。这让我一无所知。任何帮助将不胜感激!

class CustomCollectionViewLayout: UICollectionViewLayout {
    //...
    override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
        let attributes : NSMutableArray = NSMutableArray()
        for section in self.itemAttributes {
            attributes.addObjectsFromArray(
                section.filteredArrayUsingPredicate(
                    NSPredicate(block: { (evaluatedObject, bindings) -> Bool in
                        return CGRectIntersectsRect(rect, evaluatedObject.frame)
                    })
                )
            )
        }
        return attributes as [AnyObject]
    }
}

您声明了错误的 return 类型,这就是为什么编译器不允许您使用 override,并且您没有 重载 方法,要么,因为重载方法必须具有不同的 parameter 类型;仅具有不同的 return 类型是不够的。此方法的正确签名是 func layoutAttributesForElementsInRect(_ rect: CGRect) -> [UICollectionViewLayoutAttributes]?.

并且在我们进行时,请勿使用 let attributes : NSMutableArray = NSMutableArray()。不仅类型说明符 : NSMutableArray 是多余的(因为编译器可以从右侧推断类型),而且使用 Swift 的内置 Array 更容易。只需将它从 let (只读)更改为 var 即可使其可变。换句话说,var attributes = [UICollectionViewLayoutAttributes]()更好。