How to resize UITextView text which fit on its frame after scale?

683 Views Asked by At

i do following code after scale uitextview but its not given me exact result

UITextView *textView = (UITextView *)[mainView viewWithTag:10];

int newFontSize,oldFontSize;

oldFontSize = textView.font.pointSize;
newFontSize =((textView.frame.size.height * textView.frame.size.width) * oldFontSize) / (textView.contentSize.height * textView.contentSize.width);

double olddistance = sqrt(pow((textView.frame.origin.x - (textView.frame.origin.x + textView.contentSize.width)), 2.0) + pow((textView.frame.origin.y - (textView.frame.origin.y + textView.contentSize.height)), 2.0));
double newDistance = sqrt(pow((textView.frame.origin.x - (textView.frame.origin.x + textView.frame.size.width)), 2.0) + pow((textView.frame.origin.y - (textView.frame.origin.y + textView.frame.size.height)), 2.0));

float scale = newDistance/olddistance;
float newWidth  = scale * textView.contentSize.width;
float newHeight  = scale * textView.contentSize.height;

self.frame = CGRectMake(self.frame.origin.x,self.frame.origin.y, newWidth+40, newHeight+40);

if (textView.font.pointSize * scale < 10)
{
    textView.font = [UIFont fontWithName:textView.font.fontName size:10];
    self.frame = CGRectMake(self.frame.origin.x,self.frame.origin.y, textView.contentSize.width,textView.contentSize.height);
}
else
{
     textView.font = [UIFont fontWithName:textView.font.fontName size:textView.font.pointSize * scale];
}
1

There are 1 best solutions below

0
On

I have once made a text view which resizes itself to exactly fit all the text in. What you need is to provide the text and the width of your text view.

Here is the code:

-(CGSize) sizeForString:(NSString *)string WithWidth:(CGFloat)width {

    CGSize size = [string sizeWithFont:[UIFont boldSystemFontOfSize:16]
                      constrainedToSize:CGSizeMake(width, MAXFLOAT)
                            lineBreakMode:NSLineBreakByWordWrapping];

    return size;
}

The function returns the proper size for your text view, therefore, you may adjust the text view accordingly.