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
}
}
2
Answers
I ended up adding this code to the tableview cellforrowat index path function in order to get the images rendering correctly.
One decently easy way to do this is to create a custom view cell and hide the imageView if needed.
Create the custom tableView cell and make sure to add a .xib file to be able to edit everything visually:
Set the row height to automatic so that the tableView knows to set the height to whatever you need.
Then, you can add your text and imageView onto this custom cell. The way I’ve gotten this to work before is to add both elements into a stackView and set up constraints on that.
Make sure you have constraints set up for the height the label and imageView inside of the stackView and the distance from the stackView to the bottom and top of the superView. This lets auto layout know how tall to make the cell
Now, any time you hide the imageView (when you don’t have an image to display) the cell should autoresize to be smaller.