编辑 CollectionViewCell 的宽度

Editing the width of a CollectionViewCell

我正在尝试编辑单元格的宽度,这样无论屏幕尺寸如何,我都会有 score1.count 个单元格。我用于 Collection 视图的代码如下:

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 视图的单元格数量始终不正确。一种想法是,这可能是因为我在自动布局中设置了单元格大小,但每当我去更改它时 xcode 崩溃。关于绕过自动布局的任何想法?或者如何更改自动布局?

谢谢!

您可以将 sizeForItemAtIndexPath 更改为。您可以在减去边距并按单元格数潜水后分配单元格的大小。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,sizeForItemAt indexPath: IndexPath) -> CGSize {
        let size = (Int(collectionView.bounds.width) - (score1.count+1)*5) /(score1.count)  // 5 is the margin you want to keep in between 2 cells
        return CGSize(width: CGFloat(size), height: 80)
    }

如果您有任何疑问,请告诉我。我会尽力澄清。

试试这个

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)
  }

}