如果我们在U​​ILabel中设置不同类型的NSFontAttributeName,如何计算UILabel的高度?

时间:2015-11-18 10:35:08

标签: ios objective-c uilabel

当使用Attribute在一个UILable中设置不同类型的字体和颜色时,我遇到了问题。我的问题是如何获得标签的精确高度,所以我提供了高度到单元格高度并保持我的UI和文本不切割。 / p>

我试过以下事情: 代码:

     int italicHeight = [AppSingletonObj get_LblHeight:strJoin withWidth:270  withFont:_SETITALICFONT(14.0)];

    int normalTextHeight = [AppSingletonObj get_LblHeight:strCmt withWidth:270  withFont:_SETREGULARFONT(14.0)];

    int cellheight = italicHeight+normalTextHeight;

当我将帧设置为UILabel时,我使用了下面的代码

=============================================== =================

  int heightlbl = [AppSingletonObj get_LblHeight:strJoinTime withWidth:lblnotifyDesWidthAnswerQues withFont:_SETREGULARFONT(14.0)];

=============================================== ======

如果我计算出不同的高度并将高度设置为标签,那么高度会更高,文字也不适合垂直居中。

=============================================== =========

    - (CGFloat)get_LblHeight:(NSString*)str withWidth:(CGFloat)width withFont:(UIFont *)uiFont  {

        @try
        {
            // Get text
            CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
            CFAttributedStringReplaceString (attrString, CFRangeMake(0, 0), (CFStringRef) str );
            CFIndex stringLength = CFStringGetLength((CFStringRef) attrString);

            // Change font
            CTFontRef ctFont = CTFontCreateWithName((__bridge CFStringRef) uiFont.fontName, uiFont.pointSize, NULL);
            CFAttributedStringSetAttribute(attrString, CFRangeMake(0, stringLength), kCTFontAttributeName, ctFont);

            // Calc the size
            CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attrString);
            CFRange fitRange;
            CGSize frameSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, 0), NULL, CGSizeMake(width, CGFLOAT_MAX), &fitRange);

            CFRelease(ctFont);
            CFRelease(framesetter);
            CFRelease(attrString);

            return frameSize.height +05;
        }
        @catch (NSException *exception)
        {
            NSLog(@"Exception heightEmoji = %@",[exception description]);
        }
    }

=============================================== ==

enter image description here

2 个答案:

答案 0 :(得分:0)

为您的标签提供文字,然后计算框架并将该框架分配给标签。

CGRect labelSize = [label.text boundingRectWithSize:CGSizeMake(label.frame.size.width, self.view.frame.size.height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont fontWithName:@"font name" size:size]} context:nil];

答案 1 :(得分:0)

试试这个解决方案:

UILabel height calculation

它很快,但我认为你可以将它转换为objective-c