Ios 如何根据字体大小计算标签大小&;文本?
我已经在我的应用程序中的视图上添加了一个标签。我给了它一些大小,字体大小为16.0。当标签中的文本较小时,它可以正常工作。但是当文本更多地位于标签中时,我希望标签自动增加其高度并更新约束。这样我就不需要任何与约束相关的警告。最好的方法是什么这样做? 编辑Ios 如何根据字体大小计算标签大小&;文本?,ios,objective-c,ios-autolayout,Ios,Objective C,Ios Autolayout,我已经在我的应用程序中的视图上添加了一个标签。我给了它一些大小,字体大小为16.0。当标签中的文本较小时,它可以正常工作。但是当文本更多地位于标签中时,我希望标签自动增加其高度并更新约束。这样我就不需要任何与约束相关的警告。最好的方法是什么这样做? 编辑 cell.label_like_count.lineBreakMode = NSLineBreakByWordWrapping; cell.label_like_count.numberOfLines = 0; [cel
cell.label_like_count.lineBreakMode = NSLineBreakByWordWrapping;
cell.label_like_count.numberOfLines = 0;
[cell.label_like_count sizeToFit];
NSString *first_like_user=@"Some Name";
int count=[first_like_user length];
NSString *like_count=@"12";
like_count=[like_count stringByAppendingString:@" others like your post"];
first_like_user=[first_like_user stringByAppendingString:@" and "];
first_like_user=[first_like_user stringByAppendingString:like_count];
NSMutableAttributedString *mutableAttributeStr = [[NSMutableAttributedString alloc]initWithString:first_like_user];
NSAttributedString *attributeStr = [[NSAttributedString alloc]initWithString:@"\n" attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:8]}];
[mutableAttributeStr addAttribute:NSFontAttributeName value: [UIFont fontWithName:@"Helvetica-Bold" size:14.0] range:NSMakeRange(0, count)];
[mutableAttributeStr appendAttributedString:attributeStr];
我尝试了以下代码
CGSize maximumLabelSize = CGSizeMake(296,9999);
CGSize expectedLabelSize = [first_like_user sizeWithFont:cell.label_like_count.font
constrainedToSize:maximumLabelSize
lineBreakMode:cell.label_like_count.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = cell.label_like_count.frame;
newFrame.size.height = expectedLabelSize.height;
cell.label_like_count.frame = newFrame;
[cell.label_like_count setAttributedText:mutableAttributeStr];
但这不会增加标签高度&标签不会进入多行?除非指定明确的高度约束,
UILabel
s通过intrinsicContentSize
自动计算其高度约束。您所要做的就是确定标签的宽度(通过显式宽度约束或通过左/右边缘约束),它将根据内容调整其高度 我建议您在项目中添加非常有用的pod:
pod“UpdateOutLayoutConstraints”
在文件中导入必要的标题:
#import "UIView+UpdateAutoLayoutConstraints.h"
[label setText:@"some long text"];
CGFloat newHeight = [label sizeThatFits:CGSizeMake(expectedWidth, 99999999)].height;
[label setConstraintConstant:newHeight forAttribute:NSLayoutAttributeHeight];
需要增加多少高度?我怎么知道?你能告诉我不要限制UILabel的高度吗。它将自动计算必要的约束以适应其内容。你能提供五个吊舱没有工作吗