Tom H
Tom H

Reputation: 517

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);

enter image description here

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!

Upvotes: 3

Views: 4947

Answers (1)

user843910
user843910

Reputation:

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.

Upvotes: 2

Related Questions