删除 UICollectionView 单元格之间的间隙
Remove gap between UICollectionView cells
我正在尝试制作具有自由高度的灵活集合视图。但我无法消除垂直单元格之间的额外间隙。
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 上运行,当应用程序 window 调整大小时自动调整 UICollectionView 项目的大小。
On iPhone / iPad 也可以在任何方向上使用。
我正在尝试制作具有自由高度的灵活集合视图。但我无法消除垂直单元格之间的额外间隙。
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 上运行,当应用程序 window 调整大小时自动调整 UICollectionView 项目的大小。 On iPhone / iPad 也可以在任何方向上使用。