Swift:UICollectionView&UIImage致命错误:数组索引超出范围
问题描述:
嗨Im新快速,需要一些帮助谢谢。该计划曾经工作过一次,试图再次运行,然后坠毁。当我调试时,这些项目在数组中,但是当我尝试显示图像时,我得到了致命错误。Swift:UICollectionView&UIImage致命错误:数组索引超出范围
// 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
}
///////////////////////////////
结构brandCollection {
var brandText:[String] = [String]()
var brandImage:[UIImage?] = [UIImage]()
}
答
你有brands.count
项目,你需要brand.count
图像。但是,您正在使用不同的阵列pics
,如果它的元素少于brands
,将会失败。看看你的代码,为什么会发生这种情况有几种可能性。
这是不好的设计。你应该有一个数据数组来封装你需要的所有信息。每个图像应该连接到它的对象(品牌),而不是保存在其他数组中。
感谢您的回复。我甚至不知道如何做到这一点,例如? –
欢迎来到*。对不起,但你必须写自己的代码;-)。给你的品牌课一个属性'图像'并在那里存储图像。 – Mundi
我指的是YouTube视频或者其他什么,但是无论如何感谢你 –