Label 自适应文本(StoryBoard/xib)
2024-09-03 10:00:32
To make your label automatically resize height you need to do following:
- Set layout constrains for label
- Set height constraint with low priority. It should be lower than ContentCompressionResistancePriority
- Set numberOfLines = 0
- Set ContentHuggingPriority higher than label's height priority
- Set preferredMaxLayoutWidth for label. That value is used by label to calculate its height
For example:
self.descriptionLabel = [[UILabel alloc] init];
self.descriptionLabel.numberOfLines = 0;
self.descriptionLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.descriptionLabel.preferredMaxLayoutWidth = 200;
[self.descriptionLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
[self.descriptionLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
[self.descriptionLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[self addSubview:self.descriptionLabel];
NSArray* constrs = [NSLayoutConstraint constraintsWithVisualFormat:@"|-8-[descriptionLabel_]-8-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(descriptionLabel_)];
[self addConstraints:constrs];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-8-[descriptionLabel_]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(descriptionLabel_)]];
[self.descriptionLabel addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[descriptionLabel_(220@300)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(descriptionLabel_)]];
Using Interface Builder
Set up four constraints. The height constraint is mandatory.
Then go to the label's attributes inspector and set number of lines to 0.
Go to the label's size inspector and increase vertical ContentHuggingPriority and vertical ContentCompressionResistancePriority.
Select and edit height constraint.
And decrease height constraint priority.
Enjoy. :)
最新文章
- C函数
- Browser GetImage
- iOS-申请开发证书流程
- equals方法,hashcode()方法
- 笔记三、apache搭建gitweb【转】
- CreateProcess error=206, The filename or extension is too long";的一个解决方案
- Android 技术用于汇总
- 揭开CSS3媒体查询迷雾(min-width和max-width)
- mysql中 出现No query specified
- Oracle启用scott用户
- Thinkphp5.0 多图上传名称重复BUG
- psp表格记录-
- Python实现进度条功能
- 解决com.microsoft.sqlserver.jdbc.SQLServerException: 该连接已关闭
- iOS开发-ViewController的生命周期和切换
- (三)Jsoup 使用选择器语法查找 DOM 元素
- js setInterval() 用法示例
- springsecurity 表达式一览
- Android Design Support Library 中控件的使用简单介绍(一)
- Appium+python自动化27-android特有的wait_activity【转载】