如何解决如何减少 UICollection 视图中的垂直间距
我使用的 UICollectionView
下面是我的代码,如何删除垂直间距?
我尝试在 UICollectionViewFlowLayout
中进行设置,但没有奏效。
class ViewController: UIViewController {
@IBOutlet weak var cv: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
cv.register(UICollectionViewCell.self,forCellWithReuseIdentifier: "cell")
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.sectionInset = UIEdgeInsets(top: 5,left: 5,bottom: 5,right: 5)
let xx : CGFloat = (UIScreen.main.bounds.width / 8)
let yy : CGFloat = 6.0
layout.itemSize = CGSize(width: xx,height: yy)
layout.minimumInteritemSpacing = 0
layout.minimumLinespacing = 1
cv!.collectionViewLayout = layout
}
}
extension ViewController: UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
return 70
}
func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell",for: indexPath)
if (indexPath.row/2 == 0) {
cell.backgroundColor = UIColor.blue.withAlphaComponent(12)
}
else if (indexPath.row/4 == 0) {
cell.backgroundColor = UIColor.blue.withAlphaComponent(0.5)
}
else{
cell.backgroundColor = UIColor.blue.withAlphaComponent(0.1)
}
return cell
}
}
解决方法
在您的案例中,间距是由每个项目的大小 - 宽度,主要是 - 引起的。
所以你有这个代码来计算你的单项宽度:
let xx : CGFloat = (UIScreen.main.bounds.width / 8)
但由于您有部分插图,您的计算必须更改或您必须删除插图,因此:
let xx : CGFloat = (UIScreen.main.bounds.width - 10 / 8)
// 10 = 5 left + 5 right is taken for section insets
或者,删除您的部分插图:
// layout.sectionInset = UIEdgeInsets(top: 5,left: 5,bottom: 5,right: 5)
如果您想提供前导/尾随边距,请改用集合约束,即将 collectionView
约束到其超级视图的 leadingAnchor
/ trailingAnchor
常量(例如 5),然后您不必进行计算,因为您可以使用 sizeForItem
委托方法并以这种方式返回计算:
func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.bounds.width / 8,height: 5.0)
}
,
您可以使用 UICollectionViewDelegateFlowLayout
协议和 minimumInteritemSpacingForSectionAt
或 minimumLineSpacingForSectionAt
函数,如以下代码:
extension ViewController: UICollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: UICollectionView,minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 10 // or any value
}
public func collectionView(_ collectionView: UICollectionView,minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 10 // or any value
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。