Nazik
Nazik

Reputation: 8444

Issue while using `boundingRectWithSize` for aligning UILabels in dynamic frames

I have two UILabels L1 and L2.

My code,

NSString *s = @"Stringwithoutspacetext";
L1.text = s;
L2.text = @"2";


CGSize  textSize = { 150, 21 };
CGRect textRect = [[NSString stringWithFormat:@"%@",s]
        boundingRectWithSize:textSize
        options:NSStringDrawingUsesLineFragmentOrigin
        attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]}
        context:nil];

L1.frame = CGRectMake(L1.frame.origin.x, L1.frame.origin.y, textRect.size.width, L1.frame.size.height);
L2.frame = CGRectMake(L1.frame.origin.x+textRect.size.width+10, L2.frame.origin.y, L2.frame.size.width, L2.frame.size.height);

It works fine when the string s has no space in it.

enter image description here

If the string has one space, ie. s = @"String withspacetext";

output looks like below,

enter image description here

If the string has two spaces, ie. s = @"String with spacetext";

output looks like below,

enter image description here

Why the space text affects my code? What should I change in my code to work fine with the above conditions?

Upvotes: 3

Views: 493

Answers (2)

Nazik
Nazik

Reputation: 8444

Solution Found!

I just replaced the space with x in a temporary string to find the size of the textrect.

NSString *s = @"String with spacetext";
L1.text = s;
L2.text = @"2";

NSString *tempstring =[s stringByReplacingOccurrencesOfString:@" " withString:@"x"];
CGSize  textSize = { 150, 21 };
CGRect textRect = [[NSString stringWithFormat:@"%@",tempstring]
        boundingRectWithSize:textSize
        options:NSStringDrawingUsesLineFragmentOrigin
        attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]}
        context:nil];

L1.frame = CGRectMake(L1.frame.origin.x, L1.frame.origin.y, textRect.size.width, L1.frame.size.height);
L2.frame = CGRectMake(L1.frame.origin.x+textRect.size.width+10, L2.frame.origin.y, L2.frame.size.width, L2.frame.size.height);

Upvotes: 2

Mundi
Mundi

Reputation: 80271

Are these labels created in storyboard / XIB? Then you should perhaps switch off AutoLayout.

Also, numberOfLines as 0 means an infinite number of lines. This implies word wrapping which, however, is not shown due to the restricted height of your label. The word wrapping explains the phenomenon with the different lengths of string: if the second word is too long, it will break the line and show ... to indicate that not all the text is shown.

Also, adjustsFontSizeToWidth will not always work, especially if the width of the label is not fixed, which is the case here.

Also, it is better to calculate the textSize based on the font rather than hardcoding it.

Also, the stringWithFormat to format a string as a string is redundant.

BTW, variable names should not be capitalized and human readable. So label1, while still not ideal, is preferable to L1.

Upvotes: 0

Related Questions