如何获取包含换行符(\n)的UITextView的内容高度?

3

我需要计算UITextView的高度。但是,包含换行符(\n)的文本视图意味着它不能正确计算。

例如:

测试\n Lorem Ipsum仅仅是印刷和排版行业的虚拟文字\n和类型设置

如何测量带有换行符的UITextView内容的高度?

3个回答

4
只需使用以下代码即可帮助您。
NSString *strtest =@"Test \n Lorem Ipsum is simply \n dummy text of the printing \n and typesetting industry";
yourtextView.text = strtest;
CGRect framefortext = _textView.frame;
framefortext.size.height = yourtextView.contentSize.height;
yourtextView.frame = framefortext;

文本视图中的“\n”字符无法工作。它能处理换行文本吗? - Mani

1

我正在使用这段代码来查找并设置标签的确切高度,希望对你有所帮助。

[label setNumberOfLines:0];
[label sizeToFit];
int heightofbottom = label.frame.size.height;
NSLog(@"%d",heightofbottom);

0
你可以使用NSString的componentsSeparatedBy:方法和sizeWithFont:方法。
使用sizeWithFont方法获取所有组件的大小,然后总结所有高度 - 这将是结果高度,并选择最大的宽度 - 这将是结果宽度。
例如:
- (CGSize)sizeFromString:(NSString *)string {
    NSArray *componentsArray = [string componentsSeparatedBy:@"n\\"];
    CGFloat resultHeight = 0.f;
    CGFloat resultWidth = 0.f;
    for (NSString *component in componentsArray) {
        CGSize componentSize = [component sizeWithAttributes: ....]; // some attributes
        resultHeight += componentSize.height; 
        componentWidth = componentSize.width;
        if (componentWidth > resultWidth) {
            resultWidth = componentWidth
        }
    }
    return CGSizeMake(resultWidth, resultHeight);
}

也许你还应该总结一下“垂直内边距”(文本行之间的间隔)的高度。

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