UICollectionView and Parse Images ( Swift ) No Err

2019-08-18 07:06发布

问题:

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.

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

here is my function:

// 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

回答1:

Check if you are getting same count for brands and pics array.

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.