Swift:CollectionView空间

时间:2018-06-21 16:34:49

标签: ios swift

我的CollectionView中有12个单元格。我想像这样在一个屏幕上显示3个单元格:

enter image description here

并向右滚动以显示另一个单元格。

但是现在我创建了CollectionViewCollectionViewCell并在storyboard中编辑单元格,我得到了以下结果:

enter image description here

如何解决?

我在CollectionView中的代码:

import UIKit

private let reuseIdentifier = "Cell"

class MasterViewController: UICollectionViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func numberOfSections(in collectionView: UICollectionView) -> Int {

        return 1
    }


    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return 12
    }

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

        cell.label.text = String(indexPath.row)
        cell.backgroundColor = UIColor.green

        return cell
    }
}

我在CollectionViewCell中的代码:

import UIKit

class MasterViewCell: UICollectionViewCell {

    @IBOutlet weak var label: UILabel!
}

2 个答案:

答案 0 :(得分:0)

我已添加示例屏幕截图供您参考,请检查一下 仍然让您感到困惑,所以请让我知道enter image description here

答案 1 :(得分:0)

要实现该间距,您需要这样做

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 4
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 3
}

因此,在新部分中的每3个单元格之后,它将获得该部分插图,并留出该空间。

enter image description here