I have a UITextView set up in Storyboard. It is set at a defined size. I want to be able to change the size of the font based on how much text there is. The text view cannot be edited by the user and it only has to update once. Any idea how to do this?
Only UITextField
(the single line input) has adjustsFontSizeToFitWidth
and minimumFontSize
properties. With UITextView
, you'll have to program that yourself.
static const CGFloat MAX_FONT_SIZE = 16.0;
static const CGFloat MIN_FONT_SIZE = 4.0;
@interface MyViewController ()
// I haven't dealt with Storyboard / Interface builder in years,
// so this is my guess on how you link the GUI to code
@property(nonatomic, strong) IBOutlet UITextView* textView;
- (void)textDidChange:(UITextView*)textView;
@end
@implementation MyViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.textView addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
self.textView.font = [UIFont systemFontOfSize:MAX_FONT_SIZE];
}
- (void)textDidChange:(UITextView*)textView
{
// You need to adjust this sizing algorithm to your needs.
// The following is oversimplistic.
self.textView.font = [UIFont systemFontOfSize:MAX(
MAX_FONT_SIZE - textView.text.length,
MIN_FONT_SIZE
)];
}
@end
this work fine in Swift 5 :
func resizeFont(_ textView: UITextView) {
if (textView.text.isEmpty || textView.bounds.size.equalTo(CGSize.zero)) {
return;
}
let textViewSize = textView.frame.size;
let fixedWidth = textViewSize.width;
let expectSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat(MAXFLOAT)));
var expectFont = textView.font;
if (expectSize.height > textViewSize.height) {
while (textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat(MAXFLOAT))).height > textViewSize.height) {
expectFont = textView.font!.withSize(textView.font!.pointSize - 1)
textView.font = expectFont
}
}
else {
while (textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat(MAXFLOAT))).height < textViewSize.height) {
expectFont = textView.font;
textView.font = textView.font!.withSize(textView.font!.pointSize + 1)
}
textView.font = expectFont;
}
}
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