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

标签 objective-c ios nsstring uilabel

我有一个 UILabel 的子类,它应该在用户键入内容时更新其文本。自然地,随着文本长度的增加,标签的大小必须调整以适应文本。我调用了 sizeToFit 方法,当标签正确调整其宽度时,文本底部被截断。问题是文本包含下标和上标,并且标签没有根据考虑的下标进行 self 调整(例如,使用 H2O,两者的底部被截断)。

我可以重写 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)size ,如下例所示。我只是将 UILabel 计算的高度增加 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

关于objective-c - 在具有下标的 UILabel 上调用方法 sizeToFit 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8766137/

相关文章:

ios - 如何将 UIButton 带到 Mapbox View 的前面

ios - Flutter check if app was in memory when launched (How to check if splash screen is shown in iOS)

iphone - 从 NSString 中删除前导和尾随的换行符

ios - 将新数据插入核心数据存储时如何使 UICollectionView 始终位于底部

objective-c - Swift 4 将字节转换为 Int 和 ntohl

objective-c - QTCaptureSession 的 addInput 方法不返回

objective-c - 发布 UIAlertView 时的奇怪编码模式

objective-c - Objective C - iOS - 在 webViewDidFinishLoad 执行过程中调用 Dealloc

iphone - NSString @"\"添加反斜杠字符 objective-c

ios - 具有获取 NSString 条件的宏