我有以下设置:
- UIView 的自定义子类,它定义了一个固定
intrinsicContentSize
的(50,50)
- 此视图的一个实例,作为新应用程序窗口的唯一子视图
- 从视图到窗口的水平和垂直居中约束
正如预期的那样,这给了我一个 50x50 的视图,以应用程序的窗口为中心。现在,如果我两个:
- 使用 100pt 常量向视图添加所需的宽度约束,并且
- 沿水平轴将视图的内容拥抱优先级设置为必需
...为什么自动布局系统不抛出异常?
我希望这样的系统需要视图既是 50pts 宽(因为它的内在内容宽度是 50pts 并且它的拥抱优先级是必需的)和 100pts 宽(因为它在 100pts 处具有所需的显式宽度约束),因此是不一致。取而代之的是,该视图的宽度为 100 分,而(似乎)没有考虑其内容拥抱。
我用来重现此结果的整批代码(在新的空应用程序的应用委托 .m 文件中):
@interface TEFixedSizeView : UIView
@end
@implementation TEFixedSizeView
- (CGSize)intrinsicContentSize;
{
return (CGSize){.width = 50.0f, .height = 50.0f};
}
@end
@implementation TEAppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
TEFixedSizeView *view = [[TEFixedSizeView alloc] init];
view.translatesAutoresizingMaskIntoConstraints = NO;
view.backgroundColor = [UIColor redColor];
[self.window addSubview:view];
[self.window addConstraint:[NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.window
attribute:NSLayoutAttributeCenterX
multiplier:1.0f
constant:0.0f]];
[self.window addConstraint:[NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.window
attribute:NSLayoutAttributeCenterY
multiplier:1.0f
constant:0.0f]];
[view setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
[view addConstraint:[NSLayoutConstraint constraintWithItem:view
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:0.0f
constant:100.0f]];
[self.window makeKeyAndVisible];
return YES;
}
@end