0

I have a TableView that retrieves images from Parse. The image aspect ratios vary. I have it set up so that the width of the image is changed to match the width of the users device and the height will adjust to match the aspect ratio.

My problem is, whenever I run the application, the first three cells run great, but the fourth cell just takes the height from the first cell, so the image has a letter box effect. Same with the fifth and sixth cell and so on (fifth takes height of 2nd, 6th takes height of 3rd, seventh takes height of 4th which has the height of the 1st, and so on).

What would be the best way to fix this?

If you need to see more code than this, please let me know. I wasn't sure if anything else was relevant.

TableViewController

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! HomeScreenTableViewCell

    tableView.estimatedRowHeight = 100
    tableView.rowHeight = UITableViewAutomaticDimension

    //image retrieved from Parse
    imageFiles[indexPath.row].getDataInBackgroundWithBlock { (data, error) -> Void in
        if let downloadedImage = UIImage(data: data!)
        {
            cell.postedImage.image = downloadedImage
        }

    }

    cell.postId = postId[indexPath.row]
    cell.username.text = usernames[indexPath.row]
    cell.delegate = self
    return cell
}
  • You should never change tableView.estimatedRowHeight or tableView.rowHeight in cellForRowAtIndexPath: by the time this method is called its way to late to tell the tableView how big the cells should be use either heightForRowAtIndexPath or set this in viewDidLoad – DBoyer Jul 31 '15 at 16:53

2 Answers2

0

Are you implementing the heightForRowAtIndexPath method? Since you have variable heights, you have to also implement that method so whenever a new cell is created or reused, the correct height is set. You can store all heights in an array or just get it from the array images that Parse is returning. It'll be something like this in Objective C but I'm pretty sure you can do it on Swift too.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return images[indexPath.row].height;
}

Hope this helps.

0

if you want to maintain the aspect ration of the UIImageView you have to implement the heightForRow function in UITableViewDelegate like this

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
  //imageView original width is 320
  //imageView original height is 200
  let screenWidth = UIScreen.mainScreen().bounds.width
  return (screenWidth * 200) / 320
}
Firas
  • 1,742
  • 15
  • 25