简体   繁体   中英

Determining maximum font size for UITextView

Is it possible to determine maximum font size for UITextView which keeps all texts inside without cropping, while its containing text is already set and constant.

Note : I'm using custom fonts, and Swift.

You Can Calculate height of the content .Then resize your frame.

CGSize strSize= [textView.text sizeWithFont:[UIFont systemFontOfSize:17.0] constrainedToSize:CGSizeMake(290.0,99999.0)];
frame.size.height = strSize.height

Try this:

- (void)ff
{
    int minSize = 12; //define a minimum font size
    int maxSize = 60; //define a maximum font size
    int size = minSize;
    for (size = minSize; size < maxSize; size++) {
        UIFont *font = [UIFont fontWithName:@"your_font_name" size:size]; // init your font
        textView.font = font;
        [textView.layoutManager glyphRangeForTextContainer:textView.textContainer];
        NSRange visibleRange = [self visibleRangeOfTextView:textView];
        if (visibleRange.length < textView.text.length) {
            size--;
            break;
        }
    }

    NSLog(@"%d", size);

    return YES;
}

- (NSRange)visibleRangeOfTextView:(UITextView *)textView {
    CGRect bounds = textView.bounds;
    UITextPosition *start = [textView characterRangeAtPoint:bounds.origin].start;
    UITextPosition *end = [textView characterRangeAtPoint:CGPointMake(CGRectGetMaxX(bounds), CGRectGetMaxY(bounds))].end;
    return NSMakeRange([textView offsetFromPosition:textView.beginningOfDocument toPosition:start],
                       [textView offsetFromPosition:start toPosition:end]);
}

For the best results I suggest you to reset textview's paddings:

[textView setTextContainerInset:UIEdgeInsetsZero];
textView.textContainer.lineFragmentPadding = 0;

First determine Max and Min font size:-

static const CGFloat MAX_SIZE = 12.0;
static const CGFloat MIN_SIZE = 7.0;

Secondly in viewDidLoad() set maximum font size

self.txtVw.font = [UIFont systemFontOfSize:MAX_SIZE]; 

Thirdly in textView delegate method write the following code:-

- (void)textDidChange:(UITextView*)textView
{
    // This will  to adjust this sizing as per your requirement.

    self.txtVw.font = [UIFont systemFontOfSize:MAX(
        MAX_SIZE - textView.text.length, 
        MIN_SIZE
    )];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM