How to calculate the Width and Height of NSString on UILabel

I am working on a project to make the NSString on UILabel Width and Height dynamically. I tried with:

NSString *text = [messageInfo objectForKey:@"compiled"];
writerNameLabel.numberOfLines = 0;
writerNameLabel.textAlignment = UITextAlignmentRight;
writerNameLabel.backgroundColor = [UIColor clearColor];
CGSize constraint = CGSizeMake(296,9999);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] 
               constrainedToSize:constraint 
                   lineBreakMode:UILineBreakModeWordWrap];
NSLog(@"sizewidth = %f, sizeheight = %f", size.width, size.height);
NSLog(@"writerNameLabel.frame.size.width 1 -> %f",writerNameLabel.frame.size.width);
[writerNameLabel setFrame:CGRectMake(writerNameLabel.frame.origin.x, writerNameLabel.frame.origin.y, size.width, size.height)];

CGRect labelFram = writerNameLabel.frame;
labelFram.origin.x = cell.frame.size.width - writerNameLabel.frame.size.width - 80;
writerNameLabel.frame = labelFram;
NSLog(@"writerNameLabel.frame.size.width 2-> %f",writerNameLabel.frame.size.width);

Please see the green bubble not the grey one. Still not right.

The code for bubble

bubbleImageView.frame = CGRectMake(writerNameLabel.frame.origin.x, writerNameLabel.frame.origin.y, writerNameLabel.frame.size.width+15, writerNameLabel.frame.size.height+5);

Please Advise! Thanks!

Answers


That's because you did not reuse the table cell, the structure should be like:

NSString *text = [messageInfo objectForKey:@"compiled"];
if(cell == nil) 
        { 
     writerNameLabel.numberOfLines = 0;
     writerNameLabel.textAlignment = UITextAlignmentRight;
     writerNameLabel.backgroundColor = [UIColor clearColor];
     [cell addSubview:writerNameLabel];
}
else {
     writerNameLabel = (UILabel *)[cell viewWithTag:WRITER_NAME_LABEL_TAG];
}
CGSize constraint = CGSizeMake(296,9999);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] 
               constrainedToSize:constraint 
                   lineBreakMode:UILineBreakModeWordWrap];
[writerNameLabel setFrame:CGRectMake(writerNameLabel.frame.origin.x, writerNameLabel.frame.origin.y, size.width, size.height)];

I've been gone through and answered some of your question, that's correct way to write your tableview controller. And your problem will be solved.


Need Your Help

How to reload a plist file into a table

ios uitableview plist reload

I have a Plist file (outside the bundle) that I use to store the users favourites. Once loaded it works as expected the Plist is loaded into the table.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.