How to count the number of characters in a UILabel string?

I want to make a UITableview with dynamic height for a cell. In each cell I display a message with different text. Now I want my table cell to be in accordance with the message text, and also my label present in the cell should display the text. I am making the table cell flexible based on the number of characters that can fit in a row. But here is the problem. Different alphabets occupy different spaces. Thus, I cannot calculate how many letters can come in one line. Any suggestions for this ???

+6
source share
5 answers

Try the following:

 -(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 ; } 
+2
source

You do not want to count how many characters your text has, just count the height using:

 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] 

Use width for 298 and your font / font.

+1
source

Check my answer

Calculate the height of a UITableViewCell to match a string

Here you must calculate the height of the label according to the text, and then set the height of the cell.

Dynamically you can calculate the height and width using this.

I hope this helps you

0
source

Please my answer below

 UILabel *lbl = [[UILabel alloc] init]; lbl.text = @"abcd"; NSLog(@"count %lu",(unsigned long)[lbl.text length]); 
0
source
 -(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
source

All Articles