我正在关注UICollectionView上的YouTube tutorial,但是我在Swift中使用Xcode 6和iOS SDK 8.0进行编码(我也尝试使用7.1和7.0)。
这是我的控制器:
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
var imagesArray:String[] = []
let cellIdentifier = "CollectionCell"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
imagesArray += "Swift"
imagesArray += "is"
imagesArray += "the"
imagesArray += "next"
imagesArray += "hotness"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView!) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView!, numberOfItemsInSection section: Int) -> Int {
return imagesArray.count
}
func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell! {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as UICollectionViewCell
var label:UILabel = cell.viewWithTag(100) as UILabel
label.text = imagesArray[indexPath.row]
cell.layer.borderWidth = 2.0
cell.layer.borderColor = UIColor.whiteColor().CGColor
cell.layer.cornerRadius = 50.0
return cell
}
}
我已将故事板中的CollectionViewCell标识符设置为CollectionCell
,将标记设置为100
。
我正在构建应用程序,但在运行时收到此错误:
error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
The process has been returned to the state before expression evaluation.
此行发生错误:
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as UICollectionViewCell
但是,当我调试时,我注意到po indexPath
返回nil
。此外,如果我在let cell
调用后注释掉所有代码,则该应用会运行。
有什么想法吗?
答案 0 :(得分:0)
我遇到了同样的问题,为什么它失败的原因是你需要将UILabel的标签设置为100而不是UICollectionViewCell。那应该为你解决。