AutoLayout下代码更新contraints的实现
来源:互联网 发布:采集软件推荐 编辑:程序博客网 时间:2024/05/21 01:43
在很多时候,我们会遇到这样的问题,比如有一个Label,里面的内容多少是不定的,而这个label后面还紧跟这其他的UI控件,比如一个UIImageView,如果我们给Label设置一个固定的Frame,然后使用antolayout来适配。那么会出现下面的情况:当Label的内容很少时,后面的UIImageView和它之间的间距就显得比较大,而当Label的内容比较多的时候,UIImageView和它之间的间距就显得比较小。如何实现自动调节两者之间的间距呢?
下面将详细说明:
1.addObserver
[self.nameLabel addObserver:self forKeyPath:@"text" options:kNilOptions context:nil];
2.实现observer
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ if ([object isEqual:self.nameLabel]) { [self updateNameLabelContraints]; }}
3.更新约束(我这里默认最大长度为120)
- (void)updateNameLabelContraints{ NSLayoutConstraint *contraint; for (contraint in self.nameLabel.constraints) { if((contraint.firstItem == self.nameLabel) && (contraint.firstAttribute == NSLayoutAttributeWidth)) { CGSize sizeName = [self.nameLabel.text sizeWithAttributes:@{NSFontAttributeName:self.nameLabel.font}]; if(sizeName.width < 120){ contraint.constant = sizeName.width + 1; }else{ contraint.constant = 120; } } }}
0 0
- AutoLayout下代码更新contraints的实现
- AutoLayout的代码实现
- autolayout的使用原理及代码实现
- Autolayout约束的代码实现方式-1
- 代码实现系统的autoLayout布局
- iOS 使用代码实现Autolayout的方法
- Autolayout下UILabel的自动换行实现
- 代码实现 Autolayout
- AutoLayout 代码实现约束
- 代码实现AUTOLAYOUT
- 用代码实现 autolayout
- 纯代码实现 AutoLayout
- 纯代码实现AutoLayout
- 代码实现Autolayout
- Autolayout代码实现
- 代码实现Autolayout
- ios-代码实现autolayout
- 浅谈Autolayout-02代码实现Autolayout
- [note]java中的输入输出
- Java开发中的23种设计模式详解
- C++之RAII惯用法
- socket阻塞与非阻塞,同步与异步、I/O模型
- java创建多线程
- AutoLayout下代码更新contraints的实现
- ip和端口的解释
- leetcode 日经贴,Cpp code -Pow(x, n)
- vim插件配置
- office 2007 word 插入图片没有显示
- tps系统吞吐量计算公式
- Can't find keyplane that supports type 4 for keyboard iPhone-PortraitChoco-NumberPad;
- 怎样和上司谈工资?
- leetcode 日经贴,Cpp code -Plus One