UIView和intrinsicContentSize

时间:2013-01-25 18:33:33

标签: ios objective-c autolayout nslayoutconstraint

UIView是否会创建intrinsicContentSize

我创建了一个UIView contentView。我没有给它约束大小:

UIView *contentView = [UIView new];
[contentView setTranslatesAutoresizingMaskIntoConstraints:NO];
contentView.backgroundColor = [UIColor orangeColor];

我创建了另一个UIView subview01。我给它约束大小并将其添加到我的contentView:

UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[imageView setTranslatesAutoresizingMaskIntoConstraints:NO];
imageView.userInteractionEnabled = TRUE;
imageView.backgroundColor = [UIColor clearColor];

[imageView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[imageView(WIDTH)]"
                                                                  options:0
                                                                  metrics:@{@"WIDTH" : [NSNumber numberWithFloat:imageSize.width]}
                                                                    views:NSDictionaryOfVariableBindings(imageView)]];

[imageView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[imageView(HEIGHT)]"
                                                                  options:0
                                                                  metrics:@{@"HEIGHT" : [NSNumber numberWithFloat:imageSize.height]}
                                                                    views:NSDictionaryOfVariableBindings(imageView)]];


[contentView addSubview:imageView];

contentView确实没有获得任何大小。我认为intrinsicContentSize是计算显示所有子视图所需的大小并自行调整大小?就像UILabel如何调整大小以显示其所有文本一样?

2 个答案:

答案 0 :(得分:8)

不,UIView没有intrinsicContentSize。按钮和标签可以,因为系统很容易根据字符串和/或图像来计算大小。对于UIView,通常需要4个约束来完全描述其位置和大小。

答案 1 :(得分:0)

虽然不是一个完美的解决方案,但我确实想出了一种模仿intrinsicContentSize的方法。

我将容器视图的NSLayoutAttributeRight设置为最右侧子视图的NSLayoutAttributeRight,并对NSLayoutAttributeBottom执行相同的操作,以查看最低子视图' s NSLayoutAttributeBottom

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self
                                                          attribute:NSLayoutAttributeRight
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:rightSubView
                                                          attribute:NSLayoutAttributeRight
                                                         multiplier:1 constant:0]];

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self
                                                          attribute:NSLayoutAttributeBottom
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:bottumSubView
                                                          attribute:NSLayoutAttributeBottom
                                                         multiplier:1 constant:0]];