NSString sizeWithFont: returning inconsistent results? known bug?

Posted by Olof Hedman on Stack Overflow See other posts from Stack Overflow or by Olof Hedman
Published on 2010-05-31T17:56:10Z Indexed on 2010/05/31 18:23 UTC
Read the original article Hit count: 480

Filed under:
|
|
|
|

I'm trying to create a simple custom UIView wich contain a string drawn with a single font, but where the first character is slightly larger.

I thought this would be easily implemented with two UILabel:s placed next to eachother.

I use NSString sizeWithFont to measure my string to be able to lay it out correctly.

But I noticed that the font baseline in the returned rectangle varies with +/- 1 pixel depending on the font size I set. Here is my code:

NSString* ctxt = [text substringToIndex:1];
NSString* ttxt = [text substringFromIndex:1];

CGSize sz = [ctxt sizeWithFont: cfont ];
clbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, sz.width, sz.height)];
clbl.text = ctxt;
clbl.font = cfont;
clbl.backgroundColor = [UIColor clearColor];
[contentView addSubview:clbl];

CGSize sz2 = [ttxt sizeWithFont: tfont];
tlbl = [[UILabel alloc] initWithFrame:CGRectMake(sz.width, (sz.height - sz2.height), sz2.width, sz2.height)];
tlbl.text = ttxt;
tlbl.font = tfont;
tlbl.backgroundColor = [UIColor clearColor];
[contentView addSubview:tlbl];

If I use 12.0 and 14.0 as sizes, it works fine. But if I instead use 13.0 and 15.0, then the first character is 1 pixel too high.

Is this a known problem?

Any suggestions how to work around it?

Creating a UIWebView with a CSS and HTML page seems way overkill for this. and more work to handle dynamic strings. Is that what I'm expected to do?

© Stack Overflow or respective owner

Related posts about iphone

Related posts about layout