2016年9月7日 星期三

iOS tips - 'No UICollectionViewLayoutAttributes instance for -layoutAttributesForItemAtIndexPath' crash

工作寫的app中的collection view使用了custom collection view layout。最近為了一個分享的需求所以需要在開啟外部url link後捲到指定的位置,透過collectionview的function scrollToItemAtIndexPath使得collectionview跑到指定的位置。




self?.collection?.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Top, animated:true)
但是使用了這個function後我發生了如標題的crash,搜尋了一陣子才明白是因為custom layout的關係。使用了custom layout的話如果沒有overwrite layoutAttributesForItemAtIndexPath 這個function,layoutattribute是會回傳nil然後就GG了,因此在custom layout中overwrite layoutAttributesForItemAtIndexPath就解決這個crash了

override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
        return cache[indexPath.row]
}

附上參考連結
http://stackoverflow.com/questions/30562493/no-uicollectionviewlayoutattributes-instance-for-layoutattributesforitematinde





沒有留言:

張貼留言