![](/img/trans.png)
[英]How to make a collectionView with resizable cells horizontally in swift
[英]How to display particular section cells/items in centre horizontally in Collectionview Swift
我正在显示包含 3 个部分的集合视图。
每行我必须显示 4 个项目,但是,在第二行中我只需要显示 3 个项目,并且这些项目应该水平居中对齐。
我试图显示居中对齐,但是,没有按预期出来。
//UICollectionViewDatasource methods
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 1 {
return 2
} else if section == 3 {
return 4
}
return 4
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as UICollectionViewCell
cell.backgroundColor = self.randomColor()
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 2 {
// let width = (collection.bounds.width - totalSpacing)/numberOfItemsPerRow
return CGSize(width: 80, height: 60)
} else {
// let width = (collection.bounds.width - totalSpacing)/numberOfItemsPerRow
return CGSize(width: 80, height: 80)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
var cell = CGSize()
cell = CGSize(width: collectionView.frame.size.width, height:100)
return cell
}
// custom function to generate a random UIColor
func randomColor() -> UIColor{
let red = CGFloat(drand48())
let green = CGFloat(drand48())
let blue = CGFloat(drand48())
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
有什么建议么?
在第 2 部分更改集合视图布局 function。由于 static 值,即使iPad
也不会在第 1 行显示 4 个单元格。
if indexPath.section == 2 {
let width = screenWidth * 0.5 - (leadingSpace + trailerSpace)
return CGSize(width: width, height: 60)
}
extension UIViewController {
var screenWidth : CGFloat {
return UIScreen.main.bounds.size.width
}
}
考虑 iphone 11 来理解。 iphone 11的宽度是414
cellWidthAtSection2
= screenWidth * 0.5 - (leadingSpace + trailSpace)
cellWidthAtSection2
= (414 * 0.5) - (16 + 16)
cellWidthAtSection2
= 175
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.