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



我需要计算UItextview的高度。但是具有换行符的文本视图意味着它没有正确计算。前任:

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

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

只需使用以下代码可能会对您有所帮助。

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;

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

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

componentsSeparatedBy:方法和sizeWithFont: NSString方法。

使用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);
}

也许您还应该总结"垂直填充"(文本行之间的间隔(的高度

最新更新