OGeek|极客世界-中国程序员成长平台

标题: ios - 编辑 CollectionViewCell 的宽度 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:30
标题: ios - 编辑 CollectionViewCell 的宽度

我正在尝试编辑单元格的宽度,以便无论屏幕大小如何,我都会连续有 score1.count 个单元格。我用于收藏 View 的代码如下:

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.items.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell

    cell.myLabel.text = String(self.items[indexPath.item])

    return cell
}

这是针对单元格宽度的函数。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,sizeForItemAt indexPath: IndexPath) -> CGSize {
    let size = Int(self.view.frame.size.width)/(score1.count + 1)
    return CGSize(width: CGFloat(size), height: 80)
}

我花了很多时间查看不同的来源并尝试不同的东西,但 Collection View 从来没有正确数量的单元格。一个想法是,这可能是因为我在自动布局中设置了单元格大小,但是每当我去更改它时,xcode 就会崩溃。关于绕过自动布局的任何想法?或者如何改变自动布局?

谢谢!



Best Answer-推荐答案


试试这个

extension YourViewController : UICollectionViewDelegateFlowLayout{

  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let rowItems:CGFloat = 4
    let padding:CGFloat = 2
    let width = (collectionView.bounds.width / rowItems) - padding //Change width as per your requirement
    let height = collectionView.bounds.height - (2 * padding)//Change height as per your requirement
    return CGSize(width: width, height: height)
  }

}

关于ios - 编辑 CollectionViewCell 的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45665846/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4