2016-03-27 58 views
0

我在自定義單元格中獲取標籤的正確寬度時遇到問題。 這是我在故事板電池: cell in storyboardUITableViewCell:在單元格中獲取UILabel的確切寬度

在創建表,我明白,當的cellForRowAtIndexPath被調用時,小區剛剛創建,而不是添加到UITableView的呢,所以標籤的寬度爲304px。這導致的結果是這樣的:

Wrong result

滾動後,細胞已被添加到的UITableView所以它正確地顯示,與標籤的寬度是164px。

Correct result

有沒有什麼辦法可以知道電池/標籤的準確寬度之前,它被添加到UITableView的?

標籤上的限制:前置,頂部和身高 enter image description here

下面是源代碼:

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 
} 
+0

嘗試子類的tableview細胞和findout在layoutsubviews方法或initWithStyle法的範圍。 –

+1

我建議你使用自動佈局。 – tktsubota

+1

顯示cellforRow的代碼並且使用自動佈局.. –

回答

0

嘗試在func tableView(_ tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath)方法調用titleLbl.requiredHeight()

0

至於試圖獲得標籤的寬度你嘗試過某些東西的行

self.YourLabelName.bounds.width 
0

您可以使用標籤根據自動佈局顯示的文本調整其高度。

1.對於這個工作,你不應該設置靜態高度爲你的細胞,只需添加下面的兩名代表,

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath { 
     return 44; 
    } 

    -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
     return UITableViewAutomaticDimension; 
    } 

2.您應設置從上到下的約束你的細胞, 在你的情況下,你的標題標籤應該有TopSpace到Cell,LeadingSpace到ImageView,TrailingSpace到Cell(標準間距)和BottomSpace到AuthorLabel(標準間距)。

3.你想要的動態高度標籤應該已經設置爲0,LineBreakMode爲Word Wrap。

完蛋了,也發現這個鏈接類似於你的情況,

Dynamic UITableViewCell content does not expand cell

Dynamically increase height of UILabel & TableView Cell?

相關問題