ios - 自定义 UICollectionViewLayout 的 layoutAttributesForElementsInRect 不会覆盖 Swift 2.0 中其父类(super class)的任何方法

标签 ios swift uicollectionview swift2 uicollectionviewlayout

当我将我的项目从 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 选择器 'layoutAttributesForElementsInRect:' conflicts with method 'layoutAttributesForElementsInRect' from superclass 'UICollectionViewLayout' with相同的 Objective-C 选择器。这让我一无所知。任何帮助将不胜感激!

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]
    }
}

最佳答案

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

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

关于ios - 自定义 UICollectionViewLayout 的 layoutAttributesForElementsInRect 不会覆盖 Swift 2.0 中其父类(super class)的任何方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32291135/

相关文章:

ios - 将 plist 中保存的所有图像加载到 tableview 中

ios - 使用 WebSQL 的 Cordova 应用程序达到配额限制并且无法恢复

swift - 快速使用 List<String> 进行本地迁移

ios - 迭代数组时 Swift 无限循环

ios - 如何从 cellForItemAtIndexPath 设置 UICollectionViewCell 高度?

ios - 按日期用字典对数组进行排序

ios - 代码签名对于证明所有权至关重要吗?

ios - 使用 Swift 从 Objective C 库实现方法

ios - 在 sizeForItemAtIndexPath 中调用 UICollectionView Cell

ios - UICollectionView。如何在没有动画的情况下使用不同的元素(不仅是第一个)呈现 viewController?