我有一个c UIolectionView
,有时只有1个项目。如果是这种情况,则该项目在中间对齐,请参见图片:
但是我想要的是该项目向左对齐。
我在StackOverflow leftAlign cells in UIColectioniew - StackOverFlow上找到了这个答案,但是当我将接受的答案中给定的类添加到我的codeBase并将其添加到viewControler
时:
let leftAlignLayout = AlignedCollectionViewFlowLayout(horizontalAlignment: .left, verticalAlignment: .top)
gamesColectionView.collectionViewLayout = leftAlignLayout
它确实按照我想要的方式对齐,但是它使单元格非常小(参见图片)
我还尝试从Github添加此内容:AlignedCollectionViewFlowLayout - GitHub,但结果相同。
我尝试通过将其添加到我的viewController
文件中来修复该错误:
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 130, height: 130)
}
但这没用。
有人对我如何解决此问题有建议吗?我不知道自己做错了什么或忘记做什么。
非常感谢! BSM
答案 0 :(得分:1)
尝试一下:
var layout: UICollectionViewFlowLayout = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 8.0
layout.minimumInteritemSpacing = 8.0
let width = (UIScreen.main.bounds.size.width - 40.0) / 4
layout.estimatedItemSize = CGSize(width: width, height: 98.0)
return layout
}()
并且:
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView?.collectionViewLayout = layout
self.collectionView!.contentInset = UIEdgeInsets(top: 0, left: 0, bottom:0, right: 0)
}
您不需要使用sizeForItemAt。如果您想要更多,可以查看my project。通过超级视图检查imageView的约束条件
答案 1 :(得分:1)
您可以使用以下代码管理单元格。不要忘记添加UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
// your code here
}
答案 2 :(得分:1)
您无需执行任何特殊操作即可使collectionViewCells
保持对齐。
如果constraints
正确,则cells
将自动从左侧开始渲染。
class VC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 130, height: 130)
}
}
根据您在scrollDirection
本身中的要求,将vertical
设置为horizontal
或storyboard
。
无需使用任何第三方库就可以正常工作。