Search code examples
swiftxcodeuitableviewtableview

Change the height of a TableViewCell depending on if it has an image


I have a tableview that has tableview cells that are populated with users posts on the app. users are able to have posts with just text or they can include an image with their text.

The problem i have is with setting the cell height depending on if the post contains an image. for example if the post contains an image i want the cell height = 400 but if it contains only text then i want the cell height = 150.

At the moment i have the height fixed at 400 using this code but i don't know how to make the above modifications.

 func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    //auto cell height
    return 400
    
}

post model looks like this...

class Posts {
var id: String
var author: String
var text: String
var createdAt: Date
var degree: String
var university: String
var uid: String
var photoURL: String
var url: URL
var postID: String
var likes: Int

init(id:String, author:String, text:String, timestamp:Double, degree:String, university:String, uid:String, photoURL:String, url:URL, postID:String, likes:Int) {
    self.id = id
    self.author = author
    self.text = text
    self.createdAt = Date(timeIntervalSince1970: timestamp / 1000)
    self.degree = degree 
    self.university = university
    self.uid = uid
    self.photoURL = photoURL
    self.url = url
    self.postID = postID
    self.likes = likes
    
   }
}

Solution

  • I ended up adding this code to the tableview cellforrowat index path function in order to get the images rendering correctly.

    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