2010-06-18 85 views
55

我在每個單元格內都有經典的UITableView編組UITableView。此文本視圖可以是單行或多行,並且我希望單元格隨着用戶寫入和文本開始新行而增加其高度。如何動態調整UITableViewCell高度

我的問題是:我是否需要重新加載整個表格才能增加單元格的高度?沒有其他方法嗎?

我一直在尋找很多東西,以前的答案和教程只是談論如何計算文字高度,如何實現heightForRowAtIndexPath ...我已經知道的東西。我擔心的是,爲了達到我想要的水平,我將不得不計算身高,並在用戶每次輸入一個新字符時重新加載表格,而我發現這個字符並不十分乾淨或高效。

謝謝。

回答

60

您不必總是重新加載整個表格。你可以改爲重新加載一行。

[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade]; 
+0

謝謝!但我現在有另一個問題:我只是想重新加載該行來增加它的大小,我不希望單元格內容被再次實例化。但是,dequeueReusableCellWithIdentifier:@「customid」僅在第二次調用後纔開始重用。 我該怎麼辦? – araid 2010-06-22 11:55:48

+0

@rickharrison其實你可以,看看我的答案。 – 2012-10-25 08:16:02

+0

它的工作真的很好,但單元格的內容分別增長。我怎樣才能避免這種情況? – Gal 2013-04-23 08:24:14

26

更具體地講,是的,你必須實現tableView:heightForRowAtIndexPath:來計算新的高度,然後做的rickharrison說,並呼籲[tableView reloadRowsAtIndexPaths:withRowAnimation]。假設你的細胞可以有一個擴大的高度和一個正常的高度,並且你希望它們在點擊時增長。你可以這樣做:

-(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*) indexPath 
{ 
    if ([expandedPaths containsObject:indexPath]) { 
     return 80; 
    } else { 
     return 44; 
    } 
} 

-(void)tableView:(UITableView*) didSelectRowAtIndexPath:(NSIndexPath*) indexPath 
{ 
    [expandedPaths addObject:indexPath]; 
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
} 
79
[tableView beginUpdates]; 
[tableView endUpdates]; 
+13

試一下,這段代碼強制UITableView重新加載單元大小,但不是單元格內容。 – 2011-06-28 11:43:26

+0

雖然這基本上起作用,但如果將單元格增長爲使用自動行轉換重新加載單元格時,它不會產生動畫的平滑效果。 – 2012-02-22 04:08:25

+1

太棒了。如果你想在你的某些行上使用動畫,可以使用它和reloadRowsAtIndexPaths一起使用。 – 2013-05-08 06:12:49

5

-reloadRowsAtIndexPaths:withRowAnimation沒有調整的UITableViewCell高度,即使我改變了細胞的框架。它只有當我跟着它-reloadData

[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade]; 
[tableView reloadData]; 
+0

也許你引用了錯誤的indexPath,如果你調試了應用程序,你清楚地看到在你調用tableView之後reloadRowsAtIndexPath:實際調用tableView:heightForRowAtIndexPath方法。 – 2015-04-08 22:58:01