这段代码曾经在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) -> EXC_BREAKPOINT )
有人能帮我吗?
这是我从这个人那里接来的项目。https://github.com/CoderXpert/EPGGrid
发布于 2016-11-08 14:00:20
我认为你已经以某种方式把自己绑在这个话题上了。(如果我在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的结构方式不适合手头的任务(它们是字典吗?),因此需要编写代码来尝试并获得结果!不管怎样,希望这能帮上忙。
https://stackoverflow.com/questions/40475160
复制相似问题