Calling method sizeToFit on a UILabel that has sub

2020-03-21 09:58发布

I have a subclass of UILabel, which is supposed to update its text when the user types something. Naturally, as the length of text increases, the size of the label must adjust to accommodate the text. I called the sizeToFit method, and while the label adjusts its width correctly, the bottom of the text is cut off. The problem is that the text includes subscripts and superscripts , and the label is not adjusting itself with the subscripts in consideration (for example, with H₂O the bottom of the two is cut off).

Can I override sizeToFit or sizeThatFits: to increase the height of the label?

EDIT:

- (void) addCompound {

self.currentLabel = [[FormulaLabel alloc] initWithFrame:CGRectMake(10, 10, 100, 50)];

[self addSubview:self.currentLabel];

[self.currentLabel sizeToFit];

// Right now self.currentlabel.text = "". However, I've confirmed thru NSLogging that letters are added to self.currentLabel.text as the user types on the keyboard. Also, the text displays properly (as long as it's within the original frame) when I remove [sel.currentLabel sizeToFit]

}

2条回答
何必那么认真
2楼-- · 2020-03-21 10:17

This should to the trick:

self.eskLabel.adjustsFontSizeToFitWidth = YES;
查看更多
闹够了就滚
3楼-- · 2020-03-21 10:20

You should override the UILabel method (CGSize)sizeThatFits:(CGSize)size in your subclass like example below. I just add 10pt to the height calculated by UILabel to accommodate the subscript.

@implementation ESKLabel
- (CGSize)sizeThatFits:(CGSize)size
{
    CGSize theSize = [super sizeThatFits:size];
    return CGSizeMake(theSize.width, theSize.height + 10);
}
@end

Sample output:

self.eskLabel.text = @"Hello Long² Long\u2082 World";
NSLog(@"CGSize: %@", NSStringFromCGSize(self.eskLabel.frame.size));
[self.eskLabel sizeToFit];
NSLog(@"CGSize: %@", NSStringFromCGSize(self.eskLabel.frame.size));

From the NSLog:

This GDB was configured as "x86_64-apple-darwin".sharedlibrary apply-load-rules all Attaching to process 864. 
2012-01-06 23:34:21.949 Stackoverflow4[864:f803] CGSize: {85, 61} 
2012-01-06 23:34:21.951 Stackoverflow4[864:f803] CGSize: {302, 44} 
kill 
quit
查看更多
登录 后发表回答