我有一個面對的問題,當設置不同類型的字體和顏色在一個UILable使用屬性。我的問題是如何獲得標籤的確切高度,所以我已經提供了高度單元格高度和維持我的用戶界面和文本不切割。如何在UILabel中設置不同類型的NSFontAttributeName來計算UILabel的高度?
我有嘗試以下操作: CODE:
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]);
}
}
================================= ====================