AutoLayout实现 UILable自适应内容

2018-04-12  本文已影响22人  SmallWhiteMouse

今天介绍一个简单的UILabel自适应文本内容的UILabel,如何布局。
效果图镇楼
哦不,应该用妹子镇楼


现在再来效果图

这里仅仅修改了文字内容,就实现了如上效果,并且也支持屏幕旋转

我是在viewController中重写-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event方法,改变文字内容。

一、UILabel添加约束

二、代码实现

 [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);
  }];
//上
[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]];

三、注意点

如果您有什么疑问或者书写歧义,非常感激您能留言~

上一篇 下一篇

猜你喜欢

热点阅读