Calling method sizeToFit on a UILabel that has subscripts is not working

后端 未结 2 1078
天命终不由人
天命终不由人 2021-01-13 10:53

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 adju

相关标签:
2条回答
  • 2021-01-13 11:25

    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
    
    0 讨论(0)
  • 2021-01-13 11:37

    This should to the trick:

    self.eskLabel.adjustsFontSizeToFitWidth = YES;
    
    0 讨论(0)
提交回复
热议问题