获取粗体属性文本的uilabel高度



我计算标签所需高度的代码如下:

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

我从下面的代码中调用它来计算高度firs,然后用它来绘制标签

    //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粗体"不是系统字体,而是我添加的字体。

谢谢。

这是为低于iOS7的动态查找UILabel文本高度的最简单方法

CGSize fontSize = [uilabel.text sizeWithFont:uilabel.font];
NSLog(@"height %f",fontSize.height);

对于iOS7

float heightIs =[uilabel.text boundingRectWithSize:uilabel.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName:uilabel.font } context:nil].size.height;

在设置字体和每个属性后使用以下方法。

- (CGFloat)getHeight:(UILabel *)label{
      CGSize sizeOfText = [label.text boundingRectWithSize: CGSizeMake( self.bounds.size.width,CGFLOAT_MAX)
                                                  options: (NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                               attributes: [NSDictionary dictionaryWithObject:label.font
                                                forKey:NSFontAttributeName]
                                                  context: nil].size;
    return sizeOfText.height; 
    }

好的,我用下面的代码解决了这个问题:

-(float)heightOfAttrbuitedText:(NSAttributedString *)attrStr width:(CGFloat )width{
    CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(width, 10000) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
    return rect.size.height;
}

最新更新