I'm currently working on a social media app just to try and excel my Swift skills. I'm using the UIKit
framework to build this app. I've got the feed up and running, and scaling pictures correctly there went fine because I can calculate the height of an image if I know its width and aspect ratio. Now that I've starting working on the comment section, I can't solve the problem this way. I need to find a way to know what height a cell is (the comment section is a UITableView
). The problem is that to use the result from label.frame.height
, I must have set its constraints. But when setting constraints, I don't know what the height of the cell is, so it's sort of a circular problem: I don't know the height -> I can't set constraints -> I don't know the height -> ...
What I've tried is calling this function when initializing my custom UITableViewCell
(which holds the comment and the person who posted it, as well as the number of likes it has):
contentView.addSubview(label)
label.font = UIFont(name: "Arial", size: 14)
label.lineBreakMode = .byWordWrapping
label.adjustsFontSizeToFitWidth = false
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
label.topAnchor.constraint(equalTo: contentView.topAnchor, constant: padding).isActive = true
label.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: padding).isActive = true
label.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -padding).isActive = true
label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -padding).isActive = true
And my heightForRowAt indexPath
function looks like this:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let cell = CommentCell(style: .default, reuseIdentifier: Cells.commentCell)
cell.setText(to: comments[indexPath.row].text)
return cell.fetchCellHeight(with: cell.content)
}
where cell.fetchCellHeight(with:)
is defined as follows:
label.text = text
return label.frame.height
So what I've tried is setting the text and trying to read the label's height, but for some reason this returns 0.0.
So in short, what I'm wondering is how I can find the label's height so that the cells in my UITableView
get the correct height depending on how much text is in them. I'm doing this all programmatically, so unfortunately any Storyboard solution won't work for this problem unless there is a programmatic equivalent.
Thank you.