将sizeToFit与lineSpacing一起使用

时间:2014-03-24 11:23:14

标签: ios uilabel nsattributedstring sizetofit

我有一个UILabel有几行。使用这种原生方法动态设置文本,我的标签高度也是如此:

[myLabel sizeToFit];

我还有另一种方法可以设置标签中的行间距:

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"My long dynamic text"];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:5];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];


myLabel.attributedText = attributedString;

问题在于,即使我先设置行间距,然后调用sizeToFit,我标签的新高度也会很小。它不会计算行间距。

这确实是一个问题,因为我的标签位于UIScrollView,我需要正确的高度。

2 个答案:

答案 0 :(得分:1)

要根据文本长度动态获取标签大小,请使用以下方法:

/*! Returns the size of the label to display the text provided
    @param text
        The string to be displayed
    @param width
        The width required for displaying the string
    @param fontName
        The font name for the label
    @param fontSize
        The font size for the label
 */
- (CGSize)getSizeForText:(NSString *)text maxWidth:(CGFloat)width font:(NSString *)fontName fontSize:(float)fontSize {
    CGSize constraintSize;
    constraintSize.height = MAXFLOAT;
    constraintSize.width = width;
    NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                          [UIFont fontWithName:fontName size:fontSize], NSFontAttributeName,
                                          nil];

    CGRect frame = [text boundingRectWithSize:constraintSize
                                      options:NSStringDrawingUsesLineFragmentOrigin
                                   attributes:attributesDictionary
                                      context:nil];

    CGSize stringSize = frame.size;
    return stringSize;
}

答案 1 :(得分:0)

尝试使用– boundingRectWithSize:options:context:的{​​{1}}方法。有关详细信息,请参阅Apple Docs

相关问题