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

Gor*_*ilt 1 ios uicollectionview uicollectionviewlayout swift swift2

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

我试图删除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]
    }
}
Run Code Online (Sandbox Code Playgroud)

NRi*_*itH 8

您已经声明了错误的返回类型,这就是编译器不允许您使用的原因override,并且您也不会重载该方法,因为重载方法必须具有不同的参数类型; 只有不同的返回类型是不够的.这种方法的正确签名是func layoutAttributesForElementsInRect(_ rect: CGRect) -> [UICollectionViewLayoutAttributes]?.

虽然我们在这里,但不要使用let attributes : NSMutableArray = NSMutableArray().类型说明符不仅是: NSMutableArray冗余的(因为编译器可以从右侧推断出类型),但更容易使用Swift的内置函数Array.只需将其从let(只读)更改为a var即可使其变为可变.换句话说,var attributes = [UICollectionViewLayoutAttributes]()更好.