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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With