I have a custom cell that populates the tableView with users post on the app. The user can post a text message or a text message with a uiimage.
The initial problem i had was in setting the height of the cell when i contained an images. I ended up having image sin the tableview cells with ridiculous height and the images were not loading correctly.
so i added the code below to the tableView CellforRowAt function, in order to alter the frame of the images so that the UIImages loaded in a uniform size. Although this is working perfectly now, when i scroll on the tableview it is super glitchy and slow. I assume its because of the frame being altered and it takes a while to process this new frame. Is it possible to make this more efficient and smoother?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
cell.set(post: posts[indexPath.row])
cell.delegate = self
cell.commentDelegate = self
cell.likeDelegate = self
cell.selectionStyle = .none
let imageIndex = posts[indexPath.row].mediaURL
let url = NSURL(string: imageIndex)! as URL
if let imageData: NSData = NSData(contentsOf: url) {
let image = UIImage(data: imageData as Data)
let newWidth = cell.MediaPhoto.frame.width
let scale = newWidth/image!.size.width
let newHeight = image!.size.height * scale
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
image!.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
cell.MediaPhoto.image = newImage
cell.MediaPhoto.contentMode = .scaleToFill
cell.MediaPhoto.clipsToBounds = true
}
}
return cell
}
2
Answers
I ended up using this code to fix the image size to be 400 x 400 and it worked great. It doesn't render slowly or glitch anymore.
Try moving the work outside of the main thread.
}
}