美文网首页
AutoLayout实现 UILable自适应内容

AutoLayout实现 UILable自适应内容

作者: SmallWhiteMouse | 来源:发表于2018-04-12 17:33 被阅读22次

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


现在再来效果图

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

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

一、UILabel添加约束

  • 宽度 小于等于 240
  • 左边距离父视图20
  • 顶部距离父视图20
  • 底部距离父视图 小于等于 父视图底部的 -20 (没有的话会超过底屏)

二、代码实现

  • 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,就需要告诉系统不要将 AutoresizingMask 转换为约束, 即label.label.translatesAutoresizingMaskIntoConstraints = NO

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

相关文章

网友评论

      本文标题:AutoLayout实现 UILable自适应内容

      本文链接:https://www.haomeiwen.com/subject/jwkfkftx.html