UICollectionView 和解析图像(Swift)没有错误但崩溃 [英] UICollectionView and Parse Images ( Swift ) No Error but Crash
问题描述
程序启动并显示来自解析的图像,没有错误,当我再次运行它时它崩溃了.我的问题是这是否是因为图像没有缩放到自定义单元格的正确大小.
The program launched and displayed the images from parse with no error, when i ran it again it crashed. My question is if it is because the images aren't scaled to the correct size of the custom cell.
这里是错误:项目宽度必须小于 UICollectionView 的宽度减去部分插入左右值.致命错误:数组索引超出范围
here is the error: the item width must be less than the width of the UICollectionView minus the section insets left and right values. fatal error: Array index out of range
这是我的功能:
//获取品牌func getBrand() {
// 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] // here is where the warning occurs
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
推荐答案
检查品牌和图片数组的计数是否相同.
Check if you are getting same count for brands and pics array.
在您的情况下,仅当您同时使用brandImage 和BrandName 时才应附加数组.这样您的图片和品牌数组计数将相同.
In your case you should append array only if you both the brandImage and BrandName.So that your pics and brands array count will be same.
这篇关于UICollectionView 和解析图像(Swift)没有错误但崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!