这个怎么样。
代码如下。这只是一个示例,需要正确的情节提要配置。
@interface ViewController ()
@property (weak, nonatomic) IBOutlet NSLayoutConstraint * trailingConstraint;
@property (weak, nonatomic) IBOutlet UIView * blackView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint * blackViewTrailingConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint * blackViewWidthConstraint;
@property (nonatomic) BOOL preventLoop;
@end
@implementation ViewController
- (void)viewDidLoad {
super.viewDidLoad;
[self.blackView addObserver:self
forKeyPath:@"bounds"
options:0
context:nil];
}
- ( void ) observeValueForKeyPath: ( NSString * ) keyPath
ofObject: ( id ) object
change: ( NSDictionary * ) change
context: ( void * ) context
{
if ( ! self.preventLoop ) {
self.preventLoop = YES;
if ( self.blackView.bounds.size.width < 10 ) {
self.blackViewWidthConstraint.constant = 0;
self.blackViewTrailingConstraint.constant = 0;
} else {
self.blackViewTrailingConstraint.constant = 40;
}
self.preventLoop = NO;
}
}
- (IBAction)squashButtonAction:(id)sender {
self.trailingConstraint.constant += 10;
self.blackViewWidthConstraint.constant = MAX ( 0, self.blackViewWidthConstraint.constant - 10 );
}
- (IBAction)resetButtonAction:(id)sender {
self.trailingConstraint.constant = 20;
self.blackViewWidthConstraint.constant = 150;
}
@end
这个想法是使用键值观察来检测边界大小何时低于阈值;在这种情况下为 10。发生这种情况时,相关视图(此处为黑色)的宽度和尾随约束都将设置为 0。宽度在这里很明显,尾随约束是黑色视图和最后一个黄色视图之间的空间。这样你就不会得到双倍的空间。
由于您更改了观察者内部的值,因此您需要一些逻辑来防止它循环,正如您在代码中看到的那样。
黑色视图的宽度约束和紫色视图的尾随约束用于模拟视图的挤压,直到没有足够的空间容纳黑色视图。在您的特定情况下,您可能需要以不同的方式将其连接起来,但这可以完成工作,并且您有一个很好的工作示例来说明这个想法。
编辑
给猫剥皮的方法有很多种……这是另一个更简单的想法。这混合了您最初的尝试和我最初的答案的想法。您可以在其中一个布局消息中执行相同的操作,而不是使用观察者,如下所示。
我认为您的尝试与我建议的最大区别在于添加一个尾随约束(我的代码中为blackViewTrailingConstraint),然后在适当的时候使用它来将尾随空间压缩为 0。
无论如何,这里是在没有观察者的情况下完成相同操作的代码
- ( void ) viewWillLayoutSubviews {
// you could also use ...
// if ( self.blackView.bounds.size.width < 5 ) {
// ... here but it is more correct to use the width
// constaint and not the actual width here as you
// and set the constaint and the width only updates
// once layout completes
if ( self.blackViewWidthConstraint.constant < 5 ) {
self.blackViewWidthConstraint.constant = 0;
self.blackViewTrailingConstraint.constant = 0;
} else {
self.blackViewTrailingConstraint.constant = 40;
}
}