2014-02-24 126 views
1

我有自定義單元格中的tableView(單元格與textView),我想調整其中的一些單元格的大小取決於文本大小。我用下面的代碼片段這樣做:自定義單元格調整大小與文本查看

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ 
    //Load text in NSString which you want in Cell's LabelText. 

    NSString *cellText; 

    cell.Text = someData 

    //define font for Labeltext... 
    UIFont *cellFont = [UIFont fontWithName:@"Georgia" size:19.0]; 

    CGSize constraintSize = CGSizeMake(330.0f, MAXFLOAT); 

    CGSize labelSize_val = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping]; 

    return labelSize_val.height + 20; 
} 

此代碼確定在某些情況下(紅場 - 細胞的空間):

enter image description here

但隨着更大的文本它不正常工作(使空的空間更大細胞):

enter image description here

任何想法如何解決這個問題呢?

+1

是這樣的'[UIFont fontWithName:@「Georgia」size:19.0];'正是你用來顯示的字體?如果這比實際字體小,它會計算高度大得多 –

+0

是的,這是字體,用於在單元格中顯示文本 – ignotusverum

回答

0

,首先在這裏我只好重寫爲行高度在Indexpath和功能」

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ 

    NSString *cellText; 
    cellTextHeight = [self heightOfCellForText:cellText]; 
    return cellTextHeight+margin; 
     }   

    -(CGFloat)heightOfCellForText:(NSString *)yourString 
     { 


      CGRect r = [yourString boundingRectWithSize:CGSizeMake(100.0, 0) 
           options:NSStringDrawingUsesLineFragmentOrigin 
            attributes:@{NSFontAttributeName:[UIFont fontWithName:@"Arial" size:15]} context:nil]; 
      CGSize size=r.size; 
      CGFloat height=size.height; 
      return height; 
     } 

我希望這個代碼是幫助流感計算你的字符串。

0

我已經使用過這個,對我來說工作得很好。

if (SYSTEM_VERSION_LESS_THAN(@"7.0")) { 
      // code here for iOS 5.0,6.0 and so on 
      CGSize fontSize = [text sizeWithFont:[UIFont fontWithName:@"Helvetica" size:17]]; 
      size = fontSize; 
      } 
      else { 
        // code here for iOS 7.0 
        NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys: 
                  [UIFont fontWithName:@"Helvetica" size:17], NSFontAttributeName, 
                  nil]; 

        CGRect fontSizeFor7 = [text boundingRectWithSize:CGSizeMake(571, 500) 
                  options:NSStringDrawingUsesLineFragmentOrigin 
                  attributes:attributesDictionary 
                  context:nil]; 
        size = fontSizeFor7.size; 
       } 
       return size.height +20 ; 
相關問題