Maysam
Maysam

Reputation: 7367

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.

Upvotes: 5

Views: 1367

Answers (3)

arturdev
arturdev

Reputation: 11039

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;

Upvotes: 1

Deepak Thakur
Deepak Thakur

Reputation: 129

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

Upvotes: 0

Vizllx
Vizllx

Reputation: 9246

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
    )];
}

Upvotes: 0

Related Questions