关于Xcode:Xcode-UIViewController内的UICollectionView

Xcode - UICollectionView inside UIViewController

我正在尝试在UIViewController中插入集合视图:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import UIKit

class imagesViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    var labels = ["label1","label2","label3"]

    @IBOutlet weak var collectionView: UICollectionView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        self.collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier:"cell")
        collectionView.backgroundColor = UIColor.redColor()

        collectionView.delegate = self
        collectionView.dataSource = self

    }




    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        //#warning Incomplete method implementation -- Return the number of sections
        return 1
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //#warning Incomplete method implementation -- Return the number of items in the section
        return labels.count
    }


    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! UICollectionViewCell

        // Configure the cell

        var title = UILabel(frame: CGRectMake(0, 0, cell.bounds.size.width, cell.bounds.size.height))
        cell.contentView.addSubview(title)

        title.text = labels[indexPath.row]
        title.textColor = UIColor.yellowColor()

        return cell
    }

该应用程序正在运行,但集合视图似乎未正确链接到该类,我所做的所有配置均无效,它只是显示为空白。奇怪的是,我必须复制/粘贴集合视图的功能,因为自动完成仅显示某些collectionview方法。


如果您是使用StoryBoard创建单元的,那么我也遇到了同样的问题,并且可以通过删除

来解决它

1
self.collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier:"cell")

如果您在StoryBoard中定义了一个单元格,则该行似乎重复了工作并阻止了任何单元格的显示。