我的 UICollectionView 中有一个无限滚动,我注意到我估计单元格高度的方式是我的集合视图的瓶颈。我滚动收藏视图的次数越多,它就会导致一些长时间的延迟。
有没有更好的方法来估计单元格的高度?
这些单元格有不同的高度,因为我有一个UILabel
在他们每个人中。我为这些 UILabels 分配了不同长度的 NSMutableAttributedStrings:
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
My sizeForItemAt
方法。我注意到打电话dummyCell.layoutIfNeeded()
当我的集合视图中有超过 200 个项目时,我的应用程序会变得非常慢:
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)
}
Thanks!