计算UILabel高度给出错误的值



我正在尝试"预测"标签的大小(宽度是已知的,只有高度)。我正在尝试使用这个:

CGSize possibleSize = [text sizeWithFont:[UIFont fontWithName:@"American Typewriter" size:16]        
                       constrainedToSize:CGSizeMake(self.collectionView.frame.size.width ,9999)
                           lineBreakMode:NSLineBreakByWordWrapping];

这给带来了非常不准确的结果(即使更改字体和大小也不会让它变得更好,例如我得到的高度是30而不是80)。

我读到其他人用它也不会得到好的结果。我用对了吗?

我也试过:

UILabel *test=[[UILabel alloc] initWithFrame:self.collectionView.frame];
test.text=[dic objectForKey:@"text"];
test.font=[UIFont fontWithName:@"American Typewriter" size:12];
[test sizeToFit]; 
NSLog(@"%f",test.frame.size.height);

我必须知道高度是多少,而这种方法甚至还不接近。有没有其他方法可以给出合理的结果?

这个sizeWithFont方法现在被弃用,这个新方法最适合

NSString *content = **Whatever your label's content is expected to be**
CGSize maximumLabelSize = CGSizeMake(self.label.frame.size.width, 9999);
NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:[UIFont fontWithName:@"American Typewriter" size:16] forKey: NSFontAttributeName];
CGSize expectedLabelSize = [content boundingRectWithSize:maximumLabelSize options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:stringAttributes context:nil].size;
CGFloat labelHeight = expectedLabelSize.height;

其中,labelHeight是根据加载到标签中的文本量计算标签的高度。

我希望这有帮助,干杯,吉姆。

@matt您正在了解一些内容,但我要补充的是,在计算sizeWithFont之前,您应该将该标签上的行数设置为0。

您也可以尝试更换

CGSizeMake(self.collectionView.frame.size.width ,9999)

带有

CGSizeMake(self.collectionView.bounds.size.width ,FLT_MAX)

关键元素是"边界"而不是框架。

最后,确保[dic objectForKey:@"text"]不会一无所获。

使用

NSAssert(dic[@"text"]);
if ([dic[@"text"] isEqualToString:""]) {
    ; //empty string
}

首先,您需要允许UILabel是多行的,默认情况下它是一行(将行数设置为0)

yourLabel.numberOfLines = 0; // means - label can be multiline

其次,看起来你是在计算标签实际拥有的更大字体的大小。请考虑使用相同的大小,以便正确设置计算。

此外,如果您只支持iOS 7及更新版本,请考虑使用iOS 7中引入的sizeWithAttributes方法或boundingRectWithSize:options:attributes:context-替换iOS 7中使用的方法,并进一步用于文本大小计算。

最后(建议)如果您只需要该高度值来设置标签的高度,也许您应该考虑使用自动布局(这将更容易处理)。

相关内容

最新更新