gpt4 book ai didi

ios - 设置动态 UILabel 高度

转载 作者:行者123 更新时间:2023-11-29 02:22:02 24 4
gpt4 key购买 nike

我有一个带有表格 View 的应用程序需要支持动态单元格高度。在单元格的 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;
}

最佳答案

这对我有用,

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

关于ios - 设置动态 UILabel 高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28027919/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com