gpt4 book ai didi

ios - swift uicollectionview 单元格和屏幕之间没有空间,只有单元格之间

转载 作者:行者123 更新时间:2023-11-28 15:55:27 26 4
gpt4 key购买 nike

在我的 Collection View 中,我有两种布局,一种是列表,一种是网格(两列)。

当我激活列表时,每边的单元格和屏幕之间有一个 2px 的空间。

但是当我更改为网格布局时,我的单元格之间只有很小的空间,而单元格和屏幕之间没有。我想在单元格和屏幕之间添加一个 2px 的空间。

两列网格的代码:

class GridLayout: UICollectionViewFlowLayout {

var numberOfColumns: Int = 3

init(numberOfColumns: Int) {
super.init()
minimumLineSpacing = 1
minimumInteritemSpacing = 1

self.numberOfColumns = numberOfColumns
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

override var itemSize: CGSize {
get {
if let collectionView = collectionView {
let itemWidth: CGFloat = (collectionView.frame.width/CGFloat(self.numberOfColumns)) - self.minimumInteritemSpacing
let itemHeight: CGFloat = 260.0
return CGSize(width: itemWidth, height: itemHeight)
}

// Default fallback
return CGSize(width: 100, height: 100)
}
set {
super.itemSize = newValue
}
}

override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
return proposedContentOffset
}

}

以及有效列表的代码:

class ListLayout: UICollectionViewFlowLayout {

var itemHeight: CGFloat = 180

init(itemHeight: CGFloat) {
super.init()
minimumLineSpacing = 1
minimumInteritemSpacing = 1
self.itemHeight = itemHeight
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

override var itemSize: CGSize {
get {
if let collectionView = collectionView {
//Adding -4 to set a 2px space between cell and screen
let itemWidth: CGFloat = collectionView.frame.width - 4
return CGSize(width: itemWidth, height: self.itemHeight)
}

// Default fallback
return CGSize(width: 100, height: 100)
}
set {
super.itemSize = newValue
}
}

override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
return proposedContentOffset
}

}

最佳答案

UICollectionViewFlowLayoutinit 更改为:-

init(numberOfColumns: Int) {
super.init()
minimumLineSpacing = 1
minimumInteritemSpacing = 1
self.numberOfColumns = numberOfColumns

let leftPadding: CGFloat = 2.0
let rightPadding: CGFloat = 2.0
sectionInset = UIEdgeInsetsMake(0, leftPadding, 0, rightPadding)
}

并将您的 itemSize getter 方法更改为:-

get {
if let collectionView = collectionView {
let padding: CGFloat = 2.0
let itemWidth: CGFloat = (collectionView.frame.width/CGFloat(self.numberOfColumns)) - (self.minimumInteritemSpacing+ 2*padding)
let itemHeight: CGFloat = 260.0
return CGSize(width: itemWidth, height: itemHeight)
}

// Default fallback
return CGSize(width: 100, height: 100)
}

关于ios - swift uicollectionview 单元格和屏幕之间没有空间,只有单元格之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41818800/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com