Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining maximum font size for UITextView

Tags:

ios

swift

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.

like image 700
Maysam Avatar asked Nov 10 '22 13:11

Maysam


1 Answers

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;
like image 111
arturdev Avatar answered Nov 15 '22 07:11

arturdev