UITableViewCell: get the exact width of UILabel in cell
<p>I am having the problem when getting the correct width of the label in custom cell.
This is my cell in storyboard:
<a href="https://i.stack.imgur.com/yTAgf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yTAgf.png" alt="cell in storyboard"></a></p>

<p>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:</p>

<p><a href="https://i.stack.imgur.com/QsTu5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QsTu5.png" alt="Wrong result"></a></p>

<p>After scrolling, the cell has been added to the UITableView so it shows correctly, with the width of the label is 164px.</p>

<p><a href="https://i.stack.imgur.com/R9xxE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R9xxE.png" alt="Correct result"></a></p>

<p>Is there any way to know the exact width of cell/label before it is added to UITableView?</p>

<p>The constraints on the label: Leading, Trailing, Top and Height
<a href="https://i.stack.imgur.com/4Jt3O.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4Jt3O.png" alt="enter image description here"></a></p>

<p>Below is source code:</p>

<pre><code>func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; 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() &lt;--- where problem happens

    self.thumbnailImgView.imageLink(article.articleThumbnailLink!)
    self.authorLbl.text = article.articleCreator
    self.dateLbl.text = dateFormatter.stringFromDate(article.articlePubDate!)
}


extension UILabel {
func requiredHeight() -&gt; 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
}
</code></pre>