我在自定義單元格中獲取標籤的正確寬度時遇到問題。 這是我在故事板電池: UITableViewCell:在單元格中獲取UILabel的確切寬度
在創建表,我明白,當的cellForRowAtIndexPath被調用時,小區剛剛創建,而不是添加到UITableView的呢,所以標籤的寬度爲304px。這導致的結果是這樣的:
滾動後,細胞已被添加到的UITableView所以它正確地顯示,與標籤的寬度是164px。
有沒有什麼辦法可以知道電池/標籤的準確寬度之前,它被添加到UITableView的?
下面是源代碼:
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
}
嘗試子類的tableview細胞和findout在layoutsubviews方法或initWithStyle法的範圍。 –
我建議你使用自動佈局。 – tktsubota
顯示cellforRow的代碼並且使用自動佈局.. –