我正在关注 YouTube tutorial在 UICollectionView 上,但我使用 Xcode 6 和 iOS SDK 8.0(我也尝试过使用 7.1 和 7.0)在 Swift 中对其进行编码。
这是我的 Controller :
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
}
}
我已将 Storyboard 中的 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
调用之后注释掉所有代码,应用程序就会运行。
有什么想法吗?
最佳答案
我有同样的问题,它对你来说失败的原因是你需要将 UILabel 的标签设置为 100 而不是 UICollectionViewCell。这应该会为您解决问题。
关于ios - UICollectionView 示例因 EXC_BAD_INSTRUCTION 而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24530325/