更快地估算CollectionView中的单元格高度

时间:2018-05-24 22:18:25

标签: ios swift uicollectionview cgsize

我的UICollectionView中有一个无限滚动,我注意到我估计单元格高度的方式是我的集合视图的瓶颈。我滚动我的集合视图的次数越多,就会造成一些长时间的延迟。

有没有更好的方法来估计细胞的高度?

细胞的高度不同,因为我每个细胞都有一个UILabel。我将不同长度的NSMutableAttributedStrings分配给那些UILabel:

let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .justified
paragraphStyle.lineSpacing = 5.0

let attributedText = NSMutableAttributedString(string: "   \(post.caption)", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 15), .paragraphStyle: paragraphStyle, .baselineOffset: NSNumber(value: 0)])

attributedText.append(NSAttributedString(string: "\n\n", attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 4)]))

let timeAgoDisplay = post.creationDate.timeAgoDisplay()
attributedText.append(NSAttributedString(string: timeAgoDisplay, attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14), NSAttributedStringKey.foregroundColor: UIColor.storiesLightGray()]))

captionLabel.attributedText = attributedText

我的sizeForItemAt方法。我注意到,当我的集合视图中有超过200个项目时,调用dummyCell.layoutIfNeeded()会使我的应用程序变得非常慢:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        var height: CGFloat = 180

        let frame = CGRect(x: 0, y: 0, width: view.frame.width, height: height)
        let dummyCell = HomePostCell(frame: frame)

        dummyCell.post = presenter.posts[indexPath.item]
        dummyCell.layoutIfNeeded()

        let targetSize = CGSize(width: view.frame.width, height: 5000)
        let estimatedSize = dummyCell.systemLayoutSizeFitting(targetSize)

        let newHeight = max(height, estimatedSize.height)

        return CGSize(width: view.frame.width, height: newHeight)
 }

谢谢!

1 个答案:

答案 0 :(得分:4)

理想情况下,您不应在systemLayoutSizeFitting中使用sizeForItemAt,因为正如您所说,它很慢。

您可以预先缓存一些单元格数据,计算大小,并将它们存储在数组或类似数据中,这样sizeForItemAt只需要在数组中进行查找 - 这很快。

你也不需要使用systemLayoutSizeFitting;您可以使用您对标签大小和内容的了解来计算大小(例如,使用NSAttributedString测量方法)。

这就是我们在systemLayoutSizeFitting或自动布局存在之前所做的事情,它仍然快得多。