在具有下标的UILabel上调用方法sizeToFit不起作用

我有一个UILabel的子类,当用户input一些东西时,它应该更新它的文本。 当然,随着文本的长度增加,标签的大小必须调整以适应文本。 我调用了sizeToFit方法,当标签正确调整宽度时,文本的底部被切掉。 问题在于文本包括下标和上标,并且标签没有考虑下标(例如,用H 2 O将两者的底部切断)。

我可以重写sizeToFit或sizeThatFits:增加标签的高度?

编辑:

- (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] } 

你应该像下面的例子一样覆盖子类中的UILabel方法(CGSize)sizeThatFits:(CGSize)的大小。 我只是将Uptabel计算的高度加10pt来容纳下标。

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

示例输出:

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

从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 

这应该是诀窍:

 self.eskLabel.adjustsFontSizeToFitWidth = YES;