我在我的应用中的视图上添加了一个标签。我给它的字体大小为 16.0 。当标签中的文字很小时,它工作正常。但是当文本是更多标签我希望标签自动增加它的高度&也更新约束。所以我不想要任何与约束相关的警告。最好的方法是什么? 的修改
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];
但这不会增加标签高度和标签不会进入多线?
答案 0 :(得分:1)
除非您指定显式高度限制,否则UILabel
会自动通过intrinsicContentSize
计算其高度限制。您所要做的就是确定标签的宽度(通过显式宽度约束或通过左/右边缘约束),并根据内容调整其高度。
答案 1 :(得分:1)
我可以向您的项目添加非常有用的pod: pod'UpdateAutoLayoutConstraints'
在您的文件中导入必要的标题:
#import "UIView+UpdateAutoLayoutConstraints.h"
[label setText:@"some long text"];
CGFloat newHeight = [label sizeThatFits:CGSizeMake(expectedWidth, 99999999)].height;
[label setConstraintConstant:newHeight forAttribute:NSLayoutAttributeHeight];