Xcode - UIViewController 中的 UICollectionView
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31452539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Xcode - UICollectionView inside UIViewController
提问by Abdou023
I'm trying to insert a collection view inside a UIViewController:
我正在尝试在 UIViewController 中插入一个集合视图:
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
}
The app runs but it doesn't seem that the collection view is linked properly to the class, none of the configurations I made works,it just appears blank. Strangely enough I had to copy/paste the functions for the collection view because the autocomplete only shows some of the collectionview methods.
该应用程序运行,但似乎集合视图没有正确链接到类,我所做的配置都不起作用,它只是显示为空白。奇怪的是,我不得不复制/粘贴集合视图的函数,因为自动完成只显示一些集合视图方法。
回答by Joseph Geraghty
If you created your cells using StoryBoard, then I had this same problem and was able to solve it by removing
如果您使用 StoryBoard 创建了单元格,那么我遇到了同样的问题,并且能够通过删除来解决它
self.collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
That line, if you defined a cell in StoryBoard, seems to duplicate efforts and block any of the cells from displaying.
如果您在 StoryBoard 中定义了一个单元格,那一行似乎重复了工作并阻止了任何单元格的显示。