今天介紹一個簡單的UILabel自適應(yīng)文本內(nèi)容的UILabel,如何布局小泉。
效果圖鎮(zhèn)樓
哦不诫尽,應(yīng)該用妹子鎮(zhèn)樓
現(xiàn)在再來效果圖
這里僅僅修改了文字內(nèi)容,就實現(xiàn)了如上效果,并且也支持屏幕旋轉(zhuǎn)
我是在viewController中重寫
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
方法臀防,改變文字內(nèi)容。
一、UILabel添加約束
- 寬度 小于等于 240
- 左邊距離父視圖20
- 頂部距離父視圖20
- 底部距離父視圖 小于等于 父視圖底部的 -20 (沒有的話會超過底屏)
二袱衷、代碼實現(xiàn)
- Masory
[self.label mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.view.mas_left).offset(20);
make.top.equalTo(self.view.mas_top).offset(20);
make.width.mas_lessThanOrEqualTo(@240);
make.bottom.lessThanOrEqualTo(self.view.mas_bottom).offset(-20);
}];
- NSLayoutConstraint
//上
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_label attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1 constant:20]];
//左
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_label attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1 constant:20]];
//寬度少于等于240
[self.label addConstraint:[NSLayoutConstraint constraintWithItem:_label attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:240]];
//底部不超過父視圖bottom - 10
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_label attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationLessThanOrEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1 constant:-10]];
三捎废、注意點
- label.numberOfLines = 0;
- 添加約束前 一定要先將label加到父視圖
- 使用代碼NSLayoutConstraint致燥,就需要告訴系統(tǒng)不要將 AutoresizingMask 轉(zhuǎn)換為約束登疗, 即
label.label.translatesAutoresizingMaskIntoConstraints = NO
。