【问题标题】:Incorrect spacing between cells UICollectionView单元格 UICollectionView 之间的间距不正确
【发布时间】:2017-11-23 13:26:11
【问题描述】:

我有一个UICollectionView,其中包含UICollectionViewCells,其中包含UIButtons 用于内容。

但是每个单元格之间的间距不正确不正确。集合视图中的单元格没有特定的大小,因为它应该是一个长度明显不同的标签列表。

这是它的样子:

每个单元格之间的水平间距完全不正确,因为它们因行而异。

单元格的代码:

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    @IBOutlet weak var wordsCollection: UICollectionView!
    var items = ["test", "this", "word view", "like", "collection", "testing", "give", "this", "testing", "test", "test", "this", "word view", "like", "collection", "testing", "give", "this", "testing", "test", "test", "this", "word view", "like", "collection"]
    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: "wordCell", for: indexPath as IndexPath) as! WordCell
        cell.wordButton.setTitle(items[indexPath.row], for: UIControlState.normal)
        cell.wordButton.backgroundColor = UIColor.gray
        if(indexPath.row % 3 == 0){
            cell.wordButton.backgroundColor = UIColor.gray
        }
        cell.wordButton.clipsToBounds = true
        cell.wordButton.layer.cornerRadius = 2
        cell.wordButton.sizeToFit()

        return cell
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        if let flowLayout = wordsCollection.collectionViewLayout as? UICollectionViewFlowLayout { flowLayout.estimatedItemSize = CGSize(width:1, height:1) }
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

语言是 Swift 4,我的目标是 iOS 10.3。

【问题讨论】:

  • 你还没有实现 UICollectionview 的 Flow Layout 委托,然后实现方法 interItemSpacing 和 minimumLineSpacing

标签: ios uicollectionview uicollectionviewcell


【解决方案1】:

实现:UICollectionViewDelegateFlowLayout

然后:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return THE_SPACING_AMOUNT
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return SPACING_BETWEEN_ROWS
}

【讨论】:

  • 感谢您的建议!刚刚试了一下,它已经有所改善,但在某些行中仍然关闭。 i.imgur.com/yvLAu0s.png
  • 您是否要对齐它们?否则它只会尝试填充行,我猜你在单元格中使用自动布局,尝试将前导/尾随的优先级设置为 500
  • 遗憾的是两者都没有任何区别。我认为由于flowLayout.estimatedItemSize = CGSize(width:1, height:1) 在我的viewDidLoad() func 中为单元格启用了自动布局。
  • 抱歉,我认为您的 WordCell 内部存在一些混淆,标签上的前导和尾随约束优先级为 500
  • 别担心!是的,对不起,我的意思是我已经尝试了标签上的限制,优先级 500