How to calculate TextView height base on text

前端 未结 6 2022
無奈伤痛
無奈伤痛 2021-01-05 02:43

I am using the code below for calculate the height of text, then set this height for UILabel and UITextView

CGSize targetSize = CGS         


        
6条回答
  •  生来不讨喜
    2021-01-05 03:09

    Most of the answers here are hints into the right direction :-)

    So, just to sum it all up...

    UITextView uses a NSTextContainer (inside a private API _UITextContainerView) to do the real layout work. This NSTextContainer(View) may have insets to the surrounding UITextView, which are set by UITextView's textContainerInset property. The defaults for this insets seem to be:

    • top: 8
    • left: 0
    • bottom: 8
    • right: 0

    The NSTextContainer itself may have additional left and right insets for the text itself. These insets are set in NSTextContainer's lineFragmentPadding property.

    • The default for this is 5.0.

    As a result, when calculating the optimum frame size for a UITextView based on the boundingRect for some text inside that UITextView, we have to take all these insets into account:

    CGSize reservedSpace = CGSizeMake((textView.textContainerInset.left + (2.0 * textView.textContainer.lineFragmentPadding) + textView.textContainerInset.right),
                                      (textView.textContainerInset.top + textView.textContainerInset.bottom));
    CGSize targetSize = CGSizeMake((300.0 - reservedSpace.width), CGFLOAT_MAX);
    NSString* message = @"The Internet connection appears to be offline.";
    
    NSStringDrawingContext* context = [[NSStringDrawingContext alloc] init];
    CGSize boundingBox = [message boundingRectWithSize:targetSize
                                                  options:NSStringDrawingUsesLineFragmentOrigin
                                               attributes:@{NSFontAttributeName:FontOpenSanWithSize(14)}
                                                  context:context].size;
    
    CGSize size = CGSizeMake(ceil(boundingBox.width),
                             (ceil(boundingBox.height) + reservedSpace.height));
    

    Good luck :-)

提交回复
热议问题