Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

collection view cells not loading images correctly

I'm developing an iOS application that loads posts from a server into a UICollectionView. The collection view cell includes a UIImageView that is fixed to the bottom of the cell.

UICollectionViewCell

Whenever I start the application and the collection view loads, all the images do not load correctly but for the last image, which is the correct dimensions. All cells are being formatted the same way.

UICollectionView

I have tried a multitude of solutions but nothing so far has worked.

What I suspect is happening is that the images have not finished loading before being set to the UIImageView of each cell (except for the last one in this case). This doesn't seem possible though as the cells are reloaded after getting a successful response..

This is my code for that particular function (using Alamofire)

func getAllPosts(){

    let url =  "\(Constants.baseURL)/posts/"
    let parameters = ["user_id": "\(userProfile!.getId())"]

    Alamofire.request(.POST, url, parameters: parameters, encoding: .JSON)
        .validate(contentType: ["application/json"])
        .responseString { response in
            switch response.result {

            case .Success:

                var postsArray = Array<[String: AnyObject]>()

                do {

                    let json = try NSJSONSerialization.JSONObjectWithData(response.data!, options: NSJSONReadingOptions.MutableContainers)



                    for post in json as! [AnyObject] {

                        postsArray.append(post as! [String: AnyObject])

                    }

                    //invert array of posts so that latest load first!

                    postsArray = postsArray.reverse()

                } catch {

                }

                //convert json to Post objects and reload the view

                self.initialisePosts(postsArray)

                self.collectionView?.reloadData()


            case .Failure(let error):
                print(error)
            }
    }  
}

All help is appreciated.

Edit: Below are the current constraints on the UIImageView

Constraints

Edit 2: Here is the code for formatting the cells

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    // get a reference to our postcell with no image
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifiers[0], forIndexPath: indexPath) as! PostCell

    guard let _: Post? = posts[indexPath.row] else {
        return cell
    }

    return configurePostCell(cell, post: posts[indexPath.row])!
}

func configurePostCell(cell: UICollectionViewCell, post: Post) -> PostCell?{
    if let cell = cell as? PostCell {

        cell.author.text = post.user_name
        cell.date.text = formatter.stringFromDate(post.pub_date!)
        cell.desc.text = post.desc


        cell.layer.cornerRadius = 5 //set corner radius here

        cell.advertImage.image = post.advert?.advert_image


        return cell
    }

    return nil
}

Update: Using @Michael's Advice I have found that the Cell images are loading correctly..

Correctly loading image

but that the cell height is being mysteriously cropped by 50px..

Storyboard editor cell size

Storyboard editor cell size

Cell size at run-time

Cell size at run-time

This seems to be the issue but I have not found a solution yet.

Update: With two hours left on the bounty I have decided to award it to @Michael because his answer helped me to further investigation of my issue, which is still ongoing.

like image 351
Danoram Avatar asked Aug 01 '16 11:08

Danoram


People also ask

How do I delete collections from cell view?

Build and Run the project and select the Edit Button. Select a few cells and press the Trash button to remove the items.

How do I create a collection view?

Open the storyboard file in which you want to add the collection view. Press Cmd+Shift+L to open the Xcode Library and search for collection view. Select and drag the Collection View option in your screen. You will see a new blank collection view added on your screen and in left panel under Safe Area.


1 Answers

Firstly, use the Debug View Hierarchy button to check for anomalies in the table cells at runtime.

Then breakpoint on the cell creation and inspect the UIImage you are about to set to the cell and make sure the size is right. If you assign the image you downloaded to a local variable you can probably quicklook it too, to see if it looks right.

Then, if all that seems sensible, check your auto-layout code is robust.

Check by removing the downloading of images from the situation. I would do this:

  1. Remove setting of the image at all, but set the image background to UIColor.Red or something and check they all layout nicely as little more than normal UIViews.
  2. Embed an image in the app bundle as a PNG and set it instead of the downloaded image. Again, look at how it renders.
  3. Try a different sizes image in the app bundle and check again (if relevant - maybe all your images are the same size anyway)

If that all looks good, then you know it's around the download or layout of those server images.

like image 158
Michael Avatar answered Sep 20 '22 07:09

Michael