2012-08-09 75 views
2

此问题已被多次询问,但重复给出的两个或三个答案似乎不起作用。UITextView调整宽度以适应文本

问题是:一个包含一些任意文本的UITextView。在做了一些动作之后,UITextView需要在水平和垂直方向调整大小以适合文本。

对其他问题的回答给出的值看起来大约与文本的宽度/高度相同;但是,当UITextView被调整为计算大小时,它不是很正确,并且文本行分裂与原来的不同。

推荐方法包括使用– sizeWithFont:constrainedToSize:和其他的NSString方法中,UITextView的(这给出了更正确的高度,但是视图的全宽)的sizeThatFits:方法,文本视图的contentSize属性(还给出了错误的宽度)。

是否有准确的方法来确定UITextView的文本的宽度?或者是在文本视图中有一些隐藏的填充,使文本适合的实际宽度更小?还是别的我完全失踪?

+0

出于好奇,如果使用sizeWithFont方法,结果有多远? UITextView * textView = [[UITextView alloc] initWithFrame:CGRectMake(20,20,300,200)]; textView.font = [UIFont systemFontOfSize:10.0f]; (textView.contentInset.left + textView.contentInset.left),MAXFLOAT)lineBreakMode:UILineBreakModeWordWrap] [size = -1] CGSize textViewSize = [textView.text sizeWithFont:[UIFont systemFontOfSize:10.0f] constrainedToSize:CGSizeMake(textView.frame.size.width - (textView.contentInset.left + textView.contentInset.left) ; – 2012-08-09 23:30:38

+0

很难说完全是因为我没有正确的编号来比较它。内容插入全部为零。 sizeWithFont返回的大小太小,因此会增加额外的分数。如果我增加了设置文本视图的宽度[textView.text sizeWithFont:font constrainedToSize:textView.frame.size] + fudge,十六个一致似乎是给出正确大小的幻数。如果文本在一个词的中间而不是在一个空格处打破,那不起作用。在这种情况下,sizeWithFont是正确的。 – 2012-08-10 13:30:12

+0

也许空间字符不被sizeWithFont考虑,但会影响每条线如何适合uiTextView? – 2012-08-10 13:30:56

回答

0

我注意到同样的问题:NSString上的- sizeWithFont:constrainedToSize:将使用不同的换行符,而不是相同宽度的UITextView。

这是我的解决方案,但我希望找到更清洁的东西。

UITextView *tv = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, myMaxWidth, 100)]; // height resized later. 
    tv.font = myFont; 
    tv.text = @"."; // First find the min height if there is only one line. 
    [tv sizeToFit]; 
    CGFloat minHeight = tv.contentSize.height; 
    tv.text = myText; // Set the real text 
    [tv sizeToFit]; 
    CGRect frame = tv.frame; 
    frame.size.height = tv.contentSize.height; 
    tv.frame = frame; 
    CGFloat properHeight = tv.contentSize.height; 
    if (properHeight > minHeight) { // > one line 
     while (properHeight == tv.contentSize.height) { 
      // Reduce width until height increases because more lines are needed 
      frame = tv.frame; 
      frame.size.width -= 1; 
      tv.frame = frame; 
     } 
     // Add back the last point. 
     frame = tv.frame; 
     frame.size.width += 1; 
     tv.frame = frame; 
    } 
    else { // single line: ask NSString + fudge. 
     // This is needed because a very short string will never break 
     // into two lines. 
     CGSize tsz = [myText sizeWithFont:myFont constrainedToSize:tv.frame.size]; 
     frame = tv.frame; 
     frame.size.width = tsz.width + 18; // YMMV 
     tv.frame = frame; 
    } 
相关问题