AutoLayout实现 UILable自适应内容

今天介绍一个简单的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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容