在Swift中删除集合视图中的额外空格

时间:2017-03-17 11:16:33

标签: ios iphone swift uicollectionview

Desired Output like this image

代码:

let reuseIdentifier = "cell" 
var items = ["1", "2", "3", "4","5","6","7","8", "9", "10", "11","12","13","14"]

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
    // Use the outlet in our custom class to get a reference to the UILabel in the cell
    cell.myLabel.text = self.items[indexPath.item]
    cell.backgroundColor = UIColor.red
    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: CGFloat((collectionView.frame.size.width / 2) - 8), height: CGFloat(250))
}

2 个答案:

答案 0 :(得分:0)

根据您的要求这样做希望它能帮助您了解一下。

  let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
            layout.sectionInset = UIEdgeInsets(top: 10, left: 1, bottom: 5, right: 0) // according to your requirements
            layout.minimumInteritemSpacing = 1 // according to your requirements
            layout.minimumLineSpacing = 1// according to your requirements

如果您需要更多帮助或这对您不起作用,您还可以查看可以帮助您实现目标的link。点击此link

答案 1 :(得分:0)

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
 {
return CGSize(width: CGFloat((collectionView.frame.size.width / 2) - 8), height: (collectionView.frame.size. height / 3) - 8))
}