简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM