Reputation: 431
My app shows a string array that iterates through by button press. It works perfectly on all devices except iPhone 4S. The problem is some string elements are to long to fit within the UITextView and you have to scroll to read the rest of it, which I do not want.
So, my question is how to dynamically shrink attributed text to fit within a constrained UITextView when it doesn't fit all the string element?
Let me know if this is possible, Thanks guys.
Upvotes: 2
Views: 2448
Reputation: 4375
Use this in your textview category class to fit font size depend upon width.
-(BOOL)sizeFontToFit:(NSString*)aString minSize:(float)aMinFontSize maxSize:(float)aMaxFontSize
{
float fudgeFactor = 16.0;
float fontSize = aMaxFontSize;
self.font = [self.font fontWithSize:fontSize];
CGSize tallerSize = CGSizeMake(self.frame.size.width-fudgeFactor,kMaxFieldHeight);
CGSize stringSize = [aString sizeWithFont:self.font constrainedToSize:tallerSize lineBreakMode:UILineBreakModeWordWrap];
while (stringSize.height >= self.frame.size.height)
{
if (fontSize <= aMinFontSize) // it just won't fit
return NO;
fontSize -= 1.0;
self.font = [self.font fontWithSize:fontSize];
tallerSize = CGSizeMake(self.frame.size.width-fudgeFactor,kMaxFieldHeight);
stringSize = [aString sizeWithFont:self.font constrainedToSize:tallerSize lineBreakMode:UILineBreakModeWordWrap];
}
return YES;
}
Upvotes: 0
Reputation: 1107
Why are you using UITextView
, when you can use UILabel
for you situation. UITextView
does not have autoscaling property. With UILabel
you can set number of lines and it has Autoshrink
property where you can set Minimum font scale
or Minimum font size
that will adjust your text accordingly to UILabel
size. Or just allow scrolling with UITextView
.
Upvotes: 3