我正在探索使用组合布局的奇妙世界,我发现了一个需要帮助的小情况。下面是一个简单的应用程序,它使用带有 CL 的 CollectionView 来使用UIListContentConfiguration
圆形单元格显示随机字符串。该项目的宽度是.estimated(30)
这样我可以根据单元格的内容获得自定大小的单元格(宽度)。在我将字符数从 50 增加到 100 之前,这非常有效。(目前在 iPad Pro 9.7 上运行)。似乎 100 个字符超过了 CollectionView 的宽度,使我的应用程序开始使用疯狂的内存量,直到它因为同样的原因而崩溃。
如何重现:
将要显示的字符数更改为更高的数字。前任。
return (1...100).compactMap { $0; return self.randomString(length: .random(in: 1..<150))}
import UIKit
class ViewController: UICollectionViewController {
private let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
private lazy var values : [String] = {
return (1...100).compactMap { $0; return self.randomString(length: .random(in: 1..<50))}
}()
private func randomString(length: Int) -> String {
return String((0..<length).map{ _ in letters.randomElement()! })
}
var compositionalLayout : UICollectionViewCompositionalLayout = {
let inset: CGFloat = 2
//Item
let itemSize = NSCollectionLayoutSize(widthDimension: .estimated(30), heightDimension: .fractionalHeight(1))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
// Group
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(50))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
group.interItemSpacing = .fixed(4)
group.edgeSpacing = NSCollectionLayoutEdgeSpacing(leading: .fixed(4), top: .fixed(4), trailing: .fixed(0), bottom: .fixed(0))
// Section
let section = NSCollectionLayoutSection(group: group)
return UICollectionViewCompositionalLayout(section: section)
}()
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
}
private func configureUI() {
self.collectionView.collectionViewLayout = compositionalLayout
self.collectionView.dataSource = self
self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
}
}
extension ViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return values.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var contentConfiguration = UIListContentConfiguration.valueCell()
contentConfiguration.text = values[indexPath.item]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.contentConfiguration = contentConfiguration
cell.backgroundColor = UIColor(red: .random(in: 0...1) , green: .random(in: 0...1), blue: .random(in: 0...1), alpha: 1)
cell.layer.cornerRadius = cell.frame.height / 2
return cell
}
}