【问题标题】:Setting dynamic UILabel Height设置动态 UILabel 高度
【发布时间】:2015-01-19 15:19:56
【问题描述】:

我有一个需要支持动态单元格高度的表格视图应用。在单元格的layoutSubviews 方法中,我正在为我的UILabel 控件生成一个框架,这是单元格中唯一动态大小的控件。

由于某种原因,从以下方法返回的宽度小于应有的宽度,并且文本被截断,但仅限于短文本,例如一个单词。宽度应保持为作为初始帧传入的宽度。

也就是说,我的方法需要完成的是调整标签的大小以适应所有文本,同时保持预设宽度。

这是我正在使用的代码:

- (CGRect)getLabelSizeForText:(NSString*)text withInitialRect:(CGRect)labelFrame andFontSize:(CGFloat)fontSize{
    CGSize constrainedSize = CGSizeMake(labelFrame.size.width, MAXFLOAT);
    NSDictionary *attributesDict = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:fontSize], NSFontAttributeName, nil];
    CGSize requiredSize = [text boundingRectWithSize:constrainedSize
                                             options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
                                          attributes:attributesDict context:nil].size;

    CGRect adjustedFrameRect = CGRectMake(labelFrame.origin.x, labelFrame.origin.y, requiredSize.width, requiredSize.height);

    return adjustedFrameRect;
}

【问题讨论】:

  • 您可能应该根据UILabelsizeThatFits:sizeToFittextRectForBounds: 方法进行调整。

标签: ios objective-c uilabel cgrect


【解决方案1】:

这对我有用,

+ (CGSize)textSizeForText:(NSString *)text {

CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat width = screenWidth - kPaddingRight;
CGSize maxSize = CGSizeMake(width, CGFLOAT_MAX);

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 2.5;
NSDictionary *dict = @{NSParagraphStyleAttributeName : paragraphStyle, NSFontAttributeName: [UIFont systemFontOfSize:15] };
[attributedString addAttributes:dict range:NSMakeRange(0, text.length)];

CGRect paragraphRect = [attributedString boundingRectWithSize:maxSize options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) context:nil];


return paragraphRect.size;

}

【讨论】:

    猜你喜欢
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    相关资源
    最近更新 更多