IOS:动态检测字符串长度

时间:2014-07-02 03:36:23

标签: ios nsstring

有没有办法动态检测字符串高度?字符串有时足够长,可以扩展到2行,有时只有一行字符串。

CGRect frame = CGRectMake(8.0, kContentY, 200, 200);
UIWebView *tempwv = [[UIWebView alloc] initWithFrame:frame];
NSString *myHTML = @"<html><body><h1>Hello, world!</h1></body></html>";
[tempwv loadHTMLString:myHTML baseURL:nil];
NSLog(@"==========> %f", tempwv.scrollView.size.height);
[contView addSubview:tempwv];

我得到200px的高度,这是webview框架;

1 个答案:

答案 0 :(得分:1)

为此你必须指定webview的字体和字体大小和大小。在下面的方法中指定它,你将得到文本的高度。

-(CGFloat)getHeightoftext:(NSString *)str
{
    CGSize size ;
    size = [str sizeWithFont:[UIFont fontWithName:@"font-name" size:12.0] constrainedToSize:CGSizeMake(maximumWidth, maximumHeight) lineBreakMode:NSLineBreakByWordWrapping];
    return size.height ;
}

您可以使用所需的字体和字体大小测试最大高度和最大宽度。它在我的动态字符串值中适用于我。

相关问题