在很多時候,我們會遇到這樣的問題,比如有一個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;
}
}
}
}