嗨,我是 swift 新手,需要一些帮助,谢谢。该程序运行过一次,尝试再次运行它然后崩溃了。当我调试时,这些项目位于数组中,但当我尝试显示图像时,出现 fatal error 。
// Get Brands
func getBrand () {
// Create PFQuery
var query:PFQuery = PFQuery(className: "BrandInfo")
// Call findobjects
query.findObjectsInBackgroundWithBlock {
(objects:[AnyObject]?, error: NSError?) -> Void in
// refresh array
self.brands = [String]()
self.pics = [UIImage]()
// loop through array
for brandObject in objects! {
// get PFObjects
let brandName:String? = (brandObject as! PFObject)["Name"] as? String
if brandName != nil {
self.brands.append(brandName!)
}
let brandPicture = brandObject["Image"] as! PFFile
brandPicture.getDataInBackgroundWithBlock({ (imageData:NSData?, error:NSError?) -> Void in
if(error == nil){
let brandImage = UIImage(data: imageData!)
self.pics.append(brandImage)
println(self.pics.count)
}
})
}
// Refresh CollectionView
self.collectionView.reloadData()
}
}
// Setting up collection view
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.brands.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell:collectionViewCell = self.collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! collectionViewCell
// Get elements
let picToDisplay:UIImage? = pics[indexPath.row] // this is the error line
let dataToDisplay:String = brands[indexPath.row]
let imageView:UIImageView? = cell.viewWithTag(2) as? UIImageView
// Set labels
cell.brandImage.image = picToDisplay
cell.brandLabel.text = dataToDisplay
return cell
}
////////////////////////////////
结构品牌集合{
var brandText:[String] = [String]()
var brandImage:[UIImage?] = [UIImage]()
}
最佳答案
您有 brands.count
件商品,并且需要 brand.count
张图片。但是您使用的是不同的数组 pics
,如果它的元素少于 brands
,则该数组将会失败。查看您的代码,发生这种情况的可能性有多种。
这是糟糕的设计。您应该有一个数据数组,其中封装了您需要的所有信息。每个图像都应该连接到它的对象(品牌),而不是保存在其他数组中。
关于Swift:UICollectionView 和 UIImage fatal error :数组索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31503404/