- 由于无效约束,[NSView setFrame:]崩溃

时间:2013-11-29 07:36:09

标签: macos cocoa autolayout appkit nslayoutconstraint

我有典型的MVC范例:一个控制NSTableView的NSViewController。如果表视图为empt,则控制器需要在表视图的中间显示图像。显然,这个图像需要保持在超视图的中间位置,即表视图。

我这样显示:

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)” )

最后一个约束,指定x偏移444,对我来说看起来很奇怪。这似乎是不必要的,我不知道如何首先添加它。

设置自动调整遮罩而不是约束可以正常工作:

emptyPlaceholderView.autoresizingMask = NSViewMaxXMargin|NSViewMaxYMargin|NSViewMinXMargin|NSViewMinYMargin;

我做错了什么?有人可以解释一下最后一个约束来自哪里以及如何使用自动布局解决这个问题?

1 个答案:

答案 0 :(得分:0)

虽然我也试过 - [NSView setTranslatesAutoresizingMaskIntoConstraints:],但我在错误的对象上调用它。为NSImageView将此属性设置为NO可使其按预期工作。