天天看点

AutoLayout下代码更新contraints的实现

在很多时候,我们会遇到这样的问题,比如有一个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;
            }
        }
    }
}