【发布时间】:2013-11-29 07:36:09
【问题描述】:
我有典型的 MVC 范例:一个 NSViewController 控制一个 NSTableView。如果 table view 是空的,控制器需要在 table view 的中间显示一个图像。显然,这张图片需要保持在它的父视图的中间,也就是表格视图。
我是这样显示的:
NSImageView* emptyPlaceholderView = [NSImageView new];
emptyPlaceholderView.image = [NSImage messagesTableViewEmptyConversationImage];
NSSize imageSize = emptyPlaceholderView.image.size;
NSRect viewFrame = self.view.bounds;
NSRect emptyPlaceholderFrame = (NSRect){{NSMidX(viewFrame)-imageSize.width/2.0f, NSMidY(viewFrame)-imageSize.height/2.0f}, imageSize};
emptyPlaceholderView.frame = emptyPlaceholderFrame;
[self.view addSubview:emptyPlaceholderView];
[emptyPlaceholderView addConstraint:[NSLayoutConstraint constraintWithItem:emptyPlaceholderView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:NSHeight(emptyPlaceholderFrame)]];
[emptyPlaceholderView addConstraint:[NSLayoutConstraint constraintWithItem:emptyPlaceholderView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:NSWidth(emptyPlaceholderFrame)]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:emptyPlaceholderView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0f constant:0.0f]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:emptyPlaceholderView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterY multiplier:1.0f constant:0.0f]];
self.emptyPlaceholderView = emptyPlaceholderView;
这工作正常,直到我调整它所在的窗口的大小。然后它与日志一起崩溃:
2013-11-29 08:27:04.677 Messenger[924:303] Unable to simultaneously satisfy constraints:
( "NSAutoresizingMaskLayoutConstraint:0x61000028e150 h=--& v=--& H:[BTRView:0x618000153350(985)]", "NSLayoutConstraint:0x610000488390 NSImageView:0x61000017c200.centerX == BTRView:0x618000153350.centerX", "NSLayoutConstraint:0x61000048a0f0 H:[NSImageView:0x61000017c200(114)]", “NSAutoresizingMaskLayoutConstraint:0x618000498e70 h=--& v=--& H:|-(444)-[NSImageView:0x61000017c200] (名称:'|':BTRView:0x618000153350)” )
最后一个约束,它指定了 444 的 x 偏移量,对我来说看起来很奇怪。这似乎没有必要,而且我一开始并不真正了解它是如何添加的。
设置一个自动调整大小的掩码而不是约束可以正常工作:
emptyPlaceholderView.autoresizingMask = NSViewMaxXMargin|NSViewMaxYMargin|NSViewMinXMargin|NSViewMinYMargin;
我做错了什么?有人能解释一下最后一个约束来自哪里以及如何使用自动布局解决这个问题吗?
【问题讨论】:
标签: macos cocoa autolayout appkit nslayoutconstraint