2011-03-05 66 views
1

當文本比平常長時,heightForRowAtIndexPath從不顯示多行。heightForRowAtIndexPath不顯示多行

這裏是我的代碼:

#define FONT_SIZE 14.0f 
#define CELL_CONTENT_WIDTH 320.0f 
#define CELL_CONTENT_MARGIN 10.0f 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    CGFloat  result = 44.0f; 
    CGFloat  width = 0; 
    CGFloat  tableViewWidth; 
    CGRect  bounds = [UIScreen mainScreen].bounds; 

    if (UIInterfaceOrientationIsPortrait(self.interfaceOrientation)) 
     tableViewWidth = bounds.size.width; 
    else 
     tableViewWidth = bounds.size.height; 

    width = tableViewWidth - 110;  // fudge factor, 115 isn't quite right 

    NSUInteger index = [indexPath row]; 
    id doc = [[self displayedObjects] objectAtIndex:index]; 

    NSString *title = [doc title]; 

    if (title) 
    { 
     // The notes can be of any height 
     // This needs to work for both portrait and landscape orientations. 
     // Calls to the table view to get the current cell and the rect for the 
     // current row are recursive and call back this method. 
     CGSize  textSize = { width, 20000.0f };  // width and height of text area 
     CGSize  size = [title sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap]; 

     size.height += 29.0f;    // top and bottom margin 
     result = MAX(size.height, 44.0f); // at least one row 
    } 

    return result; 
} 

任何幫助將非常感激。 謝謝!

回答

3

要使標籤顯示多行文本,您必須將其numberOfLines屬性設置爲允許的最大行數(或者對於任意行數爲0)。所以在的cellForRowAtIndexPath:方法時設置你的細胞補充:

... 
cell.textLabel.numberOfLines = 0; 
... 
0

我想你不使用自定義的UITableViewCell。所以,你可能有類似於下面的代碼的東西設置標題的地方:

cell.textLabel.text = @"long long long text"; 

要獲得多行文本必須配置默認標題的UILabel,以顯示其在多行文字。就像這樣:

cell.textLabel.numberOfLines = 3; 

你可以計算行你計算單元的高度相同的方式編號。事實上,我認爲你必須計算兩者來做你想做的事(適應內容的高度)。

CGSize  size = [title sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:textSize lineBreakMode:UILineBreakModeWordWrap]; 

textSize要緊的是設置行寬度爲寬度屬性和高度值,這是「大」,足以「主機」的文字。

初始化您的size後,您可以將高度除以UILabel行的高度。

+0

嗨弗洛裏安,問題是,我不知道應該多少行文本使用(是可變的),所以設置numberOfLines = 3我想這不適用於每個單元格。 – baboso 2011-03-05 18:55:05

+0

我編輯了我的答案 – florian 2011-03-05 20:09:17