I am having the problem when getting the correct width of the label in custom cell.
This is my cell in storyboard:
When the table is created, I understand that when cellForRowAtIndexPath is called, the cell is just created and not added to UITableView yet, so the width of the label is 304px. This causes the result like this:
After scrolling, the cell has been added to the UITableView so it shows correctly, with the width of the label is 164px.
Is there any way to know the exact width of cell/label before it is added to UITableView?
The constraints on the label: Leading, Trailing, Top and Height
Below is source code:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: ArticleCell = tableView.dequeueReusableCellWithIdentifier("articleCell", forIndexPath: indexPath) as! ArticleCell
let item = array.objectAtIndex(indexPath.row) as! Article
cell.showDataForArticle(item, dateFormatter: dateFormatter)
return cell
}
func showDataForArticle(article: Article, dateFormatter: NSDateFormatter) {
self.titleLbl.text = article.articleTitle
titleHeightConstraint.constant = titleLbl.requiredHeight() <--- where problem happens
self.thumbnailImgView.imageLink(article.articleThumbnailLink!)
self.authorLbl.text = article.articleCreator
self.dateLbl.text = dateFormatter.stringFromDate(article.articlePubDate!)
}
extension UILabel {
func requiredHeight() -> CGFloat {
let frame = CGRectMake(0, 0, self.frame.size.width, CGFloat.max)
let label: UILabel = UILabel(frame: frame)
label.numberOfLines = 0
label.lineBreakMode = .ByWordWrapping
label.font = self.font
label.text = self.text
label.sizeToFit()
return label.frame.size.height
}