Yash R
Yash R

Reputation: 247

How to use dynamic height for tableviewcell

I am using UITableView to display my data from realm. I am having two types of row one with UIImageView and other without UIImageView. If there is Image in UIImageView the height of row should be 207 or UIImageView is nil the height of row should be 64.

My coding:

 func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return msgs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! collCell
    let msg = msgs[indexPath.row]
    var decodeImgURL = ""
    cell.lbl1.text = msg.content

    decodeImgURL = msg.imgurl

    if decodeImgURL == "none" {
        cell.img.isHidden = true
    } else {

        let dataDecoded : Data = Data(base64Encoded:decodeImgURL,options: .ignoreUnknownCharacters)!
        let decodedImage = UIImage(data: dataDecoded)
        cell.img.image = decodedImage

    }
    return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    let cell = tableView.cellForRow(at: indexPath) as! collCell
    if cell.img.image != nil {
        return 207
    } else {
        return 64
    }

}

I am getting an error at let cell = tableView.cellForRow(at: indexPath) as! collCell

Upvotes: 0

Views: 91

Answers (1)

DonMag
DonMag

Reputation: 77700

Use the same data in heightForRowAt as you use in cellForRowAt:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    let msg = msgs[indexPath.row]

    if msg.imgurl == "none" {
        print("row \(indexPath.row) does NOT have an image")
        return 64
    } else {
        print("row \(indexPath.row) DOES have an image")
        return 207
    }

}

Alternatively, you could use auto-layout and constraints to auto-size the height of the rows... but that's another topic.

Upvotes: 1

Related Questions