UILabel动态改变大小之前采用方法是计算出文字大小,然后重新设置frame,今天想到了一种非常简便实用的实现方法。利用了
preferredMaxLayoutWidth
属性和sizeToFit
方法
0. 后续更新(2016.06.06)
之前有点疏忽了,感觉效果对了就真的以为是这样了。其实不设置sizeToFit
也可以实现这种效果。如果文字改变了,需要更新相应的frame,经过测试必须加上
[self.resultLabel setNeedsLayout];
[self.resultLabel setNeedsLayout];
一起用才能立即更新frame。
总结来说:
- 使用autolayout设置相对位置(上下左右中心相对于一个位置即可)
-
preferredMaxLayoutWidth
设置最大宽度 -
numberOfLines
设置支持的几行(相当于设置最大高度) -
setNeedsLayout
,setNeedsLayout
立即刷新frame(如果需要的话)
1. 先看效果图
文字乱输入的,请忽略
效果图:随着字数变化改变自身的大小,宽度固定2002. 再来一波思路分析
preferredMaxLayoutWidth
:This property affects the size of the label when layout constraints are applied to it. During layout, if the text extends beyond the width specified by this property, the additional text is flowed to one or more new lines, thereby increasing the height of the label.
sizeToFit
: Call this method when you want to resize the current view so that it uses the most appropriate amount of space. Specific UIKit views resize themselves according to their own internal needs.
3. 再上个代码
@interface ViewController ()
@property (weak, nonatomic) UILabel *resultLabel;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UILabel* label = [UILabel new];
label.text = @"我是谁";
label.backgroundColor = [UIColor greenColor];
[self.view addSubview:label];
label.numberOfLines = 0;
[label sizeToFit];
self.resultLabel = label;
self.resultLabel.translatesAutoresizingMaskIntoConstraints = NO;
NSLayoutConstraint* attribureX = [NSLayoutConstraint constraintWithItem:self.resultLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0];
NSLayoutConstraint* attribureY = [NSLayoutConstraint constraintWithItem:self.resultLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0];
[self.view addConstraint:attribureX];
[self.view addConstraint:attribureY];
self.resultLabel.preferredMaxLayoutWidth = 200;
}
- (IBAction)confirm:(id)sender {
self.resultLabel.text = self.textField.text;
[self.resultLabel sizeToFit];
[self.textField resignFirstResponder];
}
@end
网友评论
补充:会根据内容使用它系统计算的intrinsicContentSize值
```
- (void)viewDidLoad {
[super viewDidLoad];
UILabel *label = ({
UILabel *label = [UILabel new];
[self.view addSubview:label];
[label makeConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(self.view);
}];
label.text = @"LaiYoung";
label;
});
self.label = label;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
self.label.text = [self.label.text stringByAppendingString:@",Hello"];
}
```