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

时间:2013-10-09 12:10:52

标签: ios uitextview

我需要计算UItextview的高度。但是具有新行(\ n)字符的文本视图意味着,它没有正确计算。 例如:

测试 \ n Lorem Ipsum只是 \ n 打印的虚拟文本 \ n 和排版行业

如何使用新行字符测量UITextView内容高度?

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:1)

我正在使用此代码来查找和设置标签的确切高度,希望它对您也有帮助

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

答案 2 :(得分:0)

您可以使用componentsSeparatedBy:方法和NSString的sizeWithFont:方法。

使用sizeWithFont方法获取所有组件大小,然后汇总所有高度 - 它 将结果高,并选择最大宽度 - 它将是结果宽度。

f.e。

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

也许你应该总结一下"垂直填充物的高度" (文本行之间的间隔)

相关问题