ios - 消除 UICollectionView 单元格之间的间隙
问题描述
我正在尝试制作具有自由高度的灵活collectionview。但我无法垂直消除单元格之间的额外间隙。
collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
collectionView.register(MultilineLabelCell.self, forCellWithReuseIdentifier: MultilineLabelCell.reuseId)
view.addSubview(collectionView)
collectionView.backgroundColor = .white
collectionView.contentInsetAdjustmentBehavior = .always
collectionView.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
collectionView.frame = self.view.bounds
collectionView.dataSource = self
collectionView.delegate = self
(collectionView.collectionViewLayout as! UICollectionViewFlowLayout).estimatedItemSize = UICollectionViewFlowLayout.automaticSize
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MultilineLabelCell.reuseId, for: indexPath) as! MultilineLabelCell
cell.configure(note: viewModel.notes![indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewModel.notes!.count
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let referenceHeight: CGFloat = 100 // Approximate height of cell
let referenceWidth = collectionView.safeAreaLayoutGuide.layoutFrame.width/2.2
return CGSize(width: referenceWidth, height: referenceHeight)
}
解决方案
你可以像这样得到一个 UICollectionView。
为此,我在我的应用程序中为自定义 UICollectionViewLayout 使用以下代码(我没有更改它,但方法本身很容易理解)
import UIKit
protocol StoryAppCollectionLayoutDelegate: AnyObject {
func collectionView(_ collectionView: UICollectionView, heightForPhotoAtIndexPath indexPath: IndexPath) -> CGFloat
}
class StoryAppCollectionLayout: UICollectionViewLayout {
weak var delegate: StoryAppCollectionLayoutDelegate?
private var numberOfColumns = 2
private let cellPadding: CGFloat = 6
private var cache: [UICollectionViewLayoutAttributes] = []
private var contentHeight: CGFloat = 0
private var previousBounds: CGRect?
private var previousNumberOfColumns : Int?
private var contentWidth: CGFloat {
guard let collectionView = collectionView else {
return 0
}
let insets = collectionView.contentInset
return collectionView.bounds.width - (insets.left + insets.right)
}
override var collectionViewContentSize: CGSize {
return CGSize(width: contentWidth, height: contentHeight)
}
override func prepare() {
if let collectionView = collectionView {
numberOfColumns = Int(collectionView.bounds.width / CARD_ITEM_SIZE)
if previousNumberOfColumns == numberOfColumns {
return
}
previousNumberOfColumns = numberOfColumns
cache.removeAll()
let columnWidth = CARD_ITEM_SIZE // contentWidth / CGFloat(numberOfColumns)
var xOffset: [CGFloat] = []
for column in 0 ..< numberOfColumns {
xOffset.append(CGFloat(column) * columnWidth)
}
var column = 0
var yOffset: [CGFloat] = .init(repeating: 0, count: numberOfColumns)
contentHeight = 0
for item in 0..<collectionView.numberOfItems(inSection: 0) {
let indexPath = IndexPath(item: item, section: 0)
let photoHeight = delegate?.collectionView(collectionView, heightForPhotoAtIndexPath: indexPath) ?? 180
let height = cellPadding * 2 + photoHeight
let frame = CGRect(x: xOffset[column],
y: yOffset[column],
width: columnWidth,
height: height)
let insetFrame = frame.insetBy(dx: cellPadding, dy: cellPadding)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = insetFrame
cache.append(attributes)
contentHeight = max(contentHeight, frame.maxY)
yOffset[column] = yOffset[column] + height
column = column < (numberOfColumns - 1) ? (column + 1) : 0
}
collectionView.contentSize.height = contentHeight
collectionView.layoutIfNeeded()
if collectionView.contentOffset.y > contentHeight - collectionView.bounds.height {
collectionView.scrollToItem(at: IndexPath(row:(collectionView.numberOfItems(inSection: 0)) - 1, section: 0), at: .bottom, animated: true)
}
}
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var visibleLayoutAttributes: [UICollectionViewLayoutAttributes] = []
// Loop through the cache and look for items in the rect
for attributes in cache {
if attributes.frame.intersects(rect) {
visibleLayoutAttributes.append(attributes)
}
}
return visibleLayoutAttributes
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return cache[indexPath.item]
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
let shouldIvalidate = newBounds != self.previousBounds
if shouldIvalidate {
if let collectionView = self.collectionView, collectionView.bounds.width > 0 {
let cWidth = CGFloat(numberOfColumns) * CARD_ITEM_SIZE
let sideInsets = (collectionView.bounds.width - cWidth) / 2
collectionView.contentInset = UIEdgeInsets(top: cellPadding, left: sideInsets, bottom: cellPadding, right: sideInsets)
collectionView.collectionViewLayout.invalidateLayout()
}
}
self.previousBounds = newBounds
return false
}
}
和
func collectionView(_ collectionView: UICollectionView, heightForPhotoAtIndexPath indexPath: IndexPath) -> CGFloat {
return CARD_ITEM_SIZE * image.size.height / image.size.width
}
希望这有助于理解这种方法。
注意。我水平使用非固定数量的元素,因为这个使用 MacCatalyst 的应用程序也适用于 MacOS,当应用程序窗口调整大小时会自动调整 UICollectionView 项的大小。在 iPhone / iPad 上也可以在任何方向使用。
推荐阅读
- c# - 检测滚动条高度和当前位置
- c - 将 PyArrayObject 传递给 C 函数
- java - Generic Exception e catch 覆盖特定异常 Java
- php - PHP-重定向到另一个页面
- python - 如果第二个元素不是重复的,则删除 2d numpy 数组的行
- ruby-on-rails - 对于具有有限可能答案的参数,首选哪种数据类型?
- javascript - 悬停其他 div JavaScript CSS 时的图像遮罩和过渡
- c++ - 如何在自定义类中调用“SetDlgItemText”?
- modbus - 用于测试的设备模拟器
- android - NestedCoordinatorLayout 内的 NestedScrollView 有时会卡住