【发布时间】:2014-09-21 15:03:48
【问题描述】:
我计算标签所需高度的代码如下:
-(float)frameForText:(NSString*)text sizeWithFont:(UIFont*)font constrainedToSize: (float)width{
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
CGRect frame = [text boundingRectWithSize:(CGSize){width, CGFLOAT_MAX} options: (NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:attributesDictionary
context:nil];
// This contains both height and width, but we really care about height.
return frame.size.height;
}
我从下面的代码中调用它来计算高度,然后用它来绘制标签
//form attributed title
NSString *str_title =@"This is sample title to calculate height";
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[paragraphStyle setLineSpacing: 2.0f];
NSDictionary *attributes = @{ NSFontAttributeName: [UIFont fontWithName:@"PTSans-Bold" size:10], NSParagraphStyleAttributeName: paragraphStyle };
NSAttributedString *attributed_title = [[NSAttributedString alloc] initWithString:str_title attributes:attributes];
//calculate height required for title
float comment_height = [self frameForText:str_title sizeWithFont:[UIFont fontWithName:@"PTSans-Bold" size:10] constrainedToSize:250];
UILabel *lbl_title;
//use calculated height here
lbl_title = [[UILabel alloc] initWithFrame:CGRectMake(60, 5, 250, title_height)];
lbl_title.numberOfLines = 0;
lbl_title.attributedText = attributed_title;
当字体为“PTSans-Regular”并给出准确的 uilabel 高度时,这可以正常工作。但是,上面的代码对“PTSans-Bold”不起作用。
我应该如何返回编写“PTSans-Bold”文本所需的确切 UIlabel,标签宽度为 250,字体大小为 10,段落行距等于 2?注意:“PTSans-Bold”不是系统字体,是我添加的字体。
谢谢。
【问题讨论】:
标签: ios objective-c uilabel uifont