UITextView调整宽度以适应文本

3
这个问题已经被问过很多次,但是重复给出的两三个答案似乎都不起作用。问题是:一个包含任意文本的`UITextView`,在某些操作后,`UITextView`需要水平和垂直地调整大小以适应文本内容。其他问题上的答案提供了一些数值,这些数值似乎是文本的大概宽度/高度;然而,当`UITextView`被调整为计算出的大小时,它并不完全正确,并且文本的换行方式与原来不同。
建议使用`-sizeWithFont:constrainedToSize:`和其他NSString方法、UITextView的`sizeThatFits:`方法(这会给出更正确的高度,但视图的完整宽度)和文本视图的`contentSize`属性(也会给出错误的宽度)。是否有一种准确的方法来确定`UITextView`文本的宽度?或者文本视图中是否有某些隐藏的填充物,使得实际上文本所适合的宽度更小?还是我完全忽略了什么东西?

出于好奇,如果使用sizeWithFont方法,结果会有多大偏差? UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 20, 300, 200)]; textView.font = [UIFont systemFontOfSize:10.0f];CGSize textViewSize = [textView.text sizeWithFont:[UIFont systemFontOfSize:10.0f] constrainedToSize:CGSizeMake(textView.frame.size.width - (textView.contentInset.left + textView.contentInset.left), MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap]; - jamie-wilson
很难准确地说,因为我没有正确的数字进行比较。内容插入都是零。sizeWithFont返回的大小太小了,所以它会添加额外的换行符。如果我增加我设置文本视图的宽度[textView.text sizeWithFont:font constrainedToSize:textView.frame.size]+fudge,那么16一直是给出正确大小的神奇数字。但是,如果文本在单词中间而不是在空格处断开,则无法正常工作。在这种情况下,sizeWithFont是正确的。 - Anthony Mattox
也许 sizeWithFont 不会考虑空格字符,但它确实会影响每行文本在 UITextView 中的适配情况? - Anthony Mattox
1个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接