如何在缩放后调整适合其框架的UITextView文本?

时间:2013-12-03 06:16:19

标签: ios fonts uitextview uifont

我在缩放uitextview后执行以下代码,但未给出确切的结果

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 个答案:

答案 0 :(得分:0)

我曾经制作了一个文本视图,它自身调整大小以完全适合所有文本。 您需要的是提供文本视图的文本和宽度。

以下是代码:

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

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

    return size;
}

该函数返回文本视图的正确大小,因此,您可以相应地调整文本视图。