2014-04-25 65 views
6

我想用單元格的動態高度製作UITableview。在每個單元格中,我都會顯示不同文字的信息。現在,我希望我的表格單元格可以根據消息的文本顯示,並且我單元格上顯示的標籤也應顯示文本。 我正在讓我的表格單元格可以容納在一行中的字符數量的基礎上靈活。但這是問題。不同的字母需要不同的空間。所以,我無法計算一行中可以有多少個字母。對此有何建議?如何計算UILabel行中有多少個字符?

+0

你試過的郵政編碼。 – Rushabh

+0

希望有些類可以處理字體。你不需要計算每個字符的字體等。 –

回答

2

試試這個:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{CGSize size; 
     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 Neue" size:19], NSFontAttributeName, 
                nil]; 
      CGRect fontSizeFor7 = [text boundingRectWithSize:CGSizeMake(571, 500) 
                options:NSStringDrawingUsesLineFragmentOrigin 
                attributes:attributesDictionary 
                context:nil]; 
      size = fontSizeFor7.size; 

     }return size.height +30 ; 

    } 
+0

其工作精細對於iOS 7,但不適用於iOS 6 – user3572586

+0

爲什麼+30? 'size.height + 30' – thedp

0

檢查我的答案

Calculate UITableViewCell height to fit string

在這裏,你必須按照文本,然後設置單元格的高度來計算標籤的高度。

您可以使用它動態計算高度和寬度。

我希望它會幫助你

+0

您正在使用: [ourText sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap]; 此方法已被棄用。 – user3572586

+0

是的,我知道...但它適用於低於7.0的ios版本。對於其他你可以找到它的替代品。我已經給你線索:) – svrushal

0

請我下面的回答

UILabel *lbl = [[UILabel alloc] init]; 
lbl.text = @"abcd"; 
NSLog(@"count %lu",(unsigned long)[lbl.text length]); 
0
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    NSString * yourCellStr = @"The string you want to apply to your cell at this index path"; 
    CGSize maxLblSize = CGSizeMake(320, 200); 
    CGSize expectedLblSize = [yourCellStr sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:maxLblSize lineBreakeMode:NSLineBreakByWordWrapping]; 

    return expectedLblSize.height; 

} 
+0

sizeWithFont方法已棄用 – user3572586

1

你不想算多少字符文本有,只需使用以下數字計算高度:

h = [NSString stringWithFormat:@"%f", 
          [post.text boundingRectWithSize:CGSizeMake(298.0f, CGFLOAT_MAX) 
          options:(NSStringDrawingUsesLineFragmentOrigin) 
          attributes:[NSDictionary dictionaryWithObject:[UIFont fontWithName:@"Helvetica Neue" size:14.0] 
          forKey: NSFontAttributeName] 
          context:nil].size.height] 

使用您的寬度爲298和您的字體/字體大小。

相關問題