1

此代码用于 swift 2.3 及更早版本。但是当我在 Swift 3 中更新它时,应用程序崩溃了。

这是 swift 2.3 中的代码

override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]?
{
    var layoutAttributes  = [UICollectionViewLayoutAttributes]()
    layoutInfo?.enumerateKeysAndObjectsUsingBlock({ (object: AnyObject, elementInfo: AnyObject, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
        let infoDic = elementInfo as! NSDictionary as NSDictionary!
        infoDic.enumerateKeysAndObjectsUsingBlock( { (object: AnyObject!, attributes: AnyObject!, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
            let attr = attributes as! UICollectionViewLayoutAttributes
            if (CGRectIntersectsRect(rect, attributes.frame))
            {
                layoutAttributes.append(attr)
            }

        })
    })

    return layoutAttributes
}

这是 Swift 3 的更新版本

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

    var layoutAttributes  = [UICollectionViewLayoutAttributes]()
    layoutInfo?.enumerateKeysAndObjects({ (object: AnyObject, elementInfo: AnyObject, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
        let infoDic = elementInfo as! NSDictionary as NSDictionary!
        infoDic?.enumerateKeysAndObjects( { (object: AnyObject!, attributes: AnyObject!, stop: UnsafeMutablePointer<ObjCBool>) -> Void in

            let attr = attributes as! UICollectionViewLayoutAttributes
            if (rect.intersects(attributes.frame))
            {
                layoutAttributes.append(attr)
            }

        } as! (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Void)
    } as! (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Void)

    return layoutAttributes
}

我在 } 时遇到了这个崩溃!(Any, Any, UnsafeMutablePointer) -> Void) EXC_BREAKPOINT

任何人都可以帮助我吗?

这是我从这个人那里得到的项目。 https://github.com/CoderXpert/EPGGrid

4

1 回答 1

1

我认为您已经设法以某种方式将自己与这个话题联系在一起。(如果我最终在 Swift 代码中使用了大量的强制转换和 ObjectiveC 类型,这对我来说总是一个警告信号)。我刚刚在我的一个应用程序中查看了 layoutAttributesForElements(in) 的实现,它归结为以下内容:

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

    var layoutAttributes = [UICollectionViewLayoutAttributes]()
    if cache.isEmpty {
        self.prepare()
    }
    for attributes in cache {
        if attributes.frame.intersects(rect) {
            layoutAttributes.append(self.layoutAttributesForItem(at: attributes.indexPath)!)
        }
    }
    return layoutAttributes
}

在这个实现中,缓存是 UICollectionViewLayoutAttributes 的数组,它在集合视图初始化或数据更改时准备好(通过 prepare() 方法)。在确保缓存不为空后,您需要做的就是遍历缓存并收集其帧与相关帧相交的任何属性。如果某个属性被捕获,请使用方法 layoutAttributesForItemAt(如果您是布局管理器的子类,则为另一个基本功能)来获取所需的值。

虽然很难确切地看到代码中发生了什么,但我认为问题在于 layoutInfo 和 infoDic 的结构方式不适合手头的任务(它们是字典吗?),因此编码体操尝试并获得结果!无论如何,希望这会有所帮助。

于 2016-11-08T14:00:19.777 回答