I have a UITableViewCell
that has a UIImageView
. Users can post images and they'll display in the UITableView
(think similar to social network/media apps).
The problem I have is that after I create my post and I am back at the main UITableView
, the cell is not resizing accordingly. But after I scroll and the cell goes off screen it updates to the correct size.
Because I am cropping the images and they can be portrait or landscape I am calculating the ratio of the image, unless they exceed a certain size then I set a constraint constant to a set size.
Here's some code to see what I am trying to do:
override func viewDidLoad() {
self.myTableView.rowHeight = UITableView.automaticDimension
self.myTableView.estimatedRowHeight = 500
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.myTableView.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell.myImageView.sd_setImage(with: imageRef, placeholderImage: nil) { (downloadedImage, error, cache, url) in
if let image = downloadedImage as? UIImage {
let ratio = image.size.width / image.size.height
var newHeight = cell.myImageView.frame.width / ratio
if newHeight >= tableView.frame.width {
newHeight = tableView.frame.width
} else {
newHeight = cell.myImageView.frame.width / ratio
}
cell.myImageHeightConstraint.constant = newHeight
if let indexPath = tableView.indexPath(for: cell) {
tableView.reloadRows(at: [indexPath], with: .none)
}
}
}
}
Update:
I feel like I'm getting closer but still having some issues. Above I have modified the code. So right now when I make my new post and the table reloads, the cell resizes with a slight animation. That's fine. Preferably I'd like the user NOT to see the cell animate to the correct size. The next issue is when I scroll down some of the cells may need to resize and it causes some jumpiness.