【发布时间】:2014-11-14 07:12:57
【问题描述】:
我是 swift 新手,我不太清楚如何解决这个错误。
我正在创建一个集合视图,这是我的代码:
import UIKit
class FlashViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// Move on ...
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
layout.itemSize = CGSize(width: 90, height: 90)
collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
self.collectionView.dataSource = self
self.collectionView.delegate = self
collectionView.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
collectionView.backgroundColor = UIColor.whiteColor()
self.view.addSubview(collectionView!)
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 20
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as CollectionViewCell
cell.backgroundColor = UIColor.blackColor()
cell.textLabel?.text = "\(indexPath.section):\(indexPath.row)"
cell.imageView?.image = UIImage(named: "circle")
return cell
}
}
每次我运行它时,self.collectionView.dataSource = self 行都会突出显示,并且出现上述错误。
【问题讨论】:
-
看来
self.collectionView是nil。确保您的 IB 网点设置正确。您使用的是故事板还是 .xib 文件? -
IBOutlet 属性应该从 Interface Builder 中设置,而很少从代码中设置,因此请确保您要在 viewDidLoad 中进行设置。
标签: ios swift uicollectionview uicollectionviewcell