防止可折叠NSSplitView的破坏约束

时间:2018-01-30 14:22:11

标签: objective-c macos autolayout nsview nssplitview

我有一个包含NSSearchField的NSSplitView。它看起来像这样:

Splitview example

我使用以下代码创建了NSSearchField:

- (void) applicationDidFinishLaunching: (NSNotification *) aNotification
{
    searchField = [[NSSearchField alloc] init];
    searchField.translatesAutoresizingMaskIntoConstraints = NO;
    [leftView addSubview: searchField];
    [searchField.leadingAnchor constraintEqualToAnchor: leftView.leadingAnchor
                                              constant: 1.0f].active = YES;
    [searchField.trailingAnchor constraintEqualToAnchor: leftView.trailingAnchor
                                               constant: -1.0f].active = YES;
    [searchField.topAnchor constraintEqualToAnchor: leftView.topAnchor
                                          constant: 1.0f].active = YES;
    [searchField.heightAnchor constraintEqualToConstant: 22.0f].active = YES;
}

这很好用,我可以毫无问题地调整分割器的大小。

但是,如果我添加以下NSSplitViewDelegate方法(尝试使左侧完全可折叠):

- (CGFloat)splitView:(NSSplitView *)splitView
constrainMinCoordinate:(CGFloat)proposedMinimumPosition
         ofSubviewAt:(NSInteger)dividerIndex
{
    if(0 == dividerIndex)
    {
        return 0;
    }

    return proposedMinimumPosition;
}

现在,如果我调整拆分器的大小以便左侧视图折叠,我会遇到约束违规。

AnchorTest[57668:1656122] [Layout] Unable to simultaneously satisfy constraints:
(
    "<NSAutoresizingMaskLayoutConstraint:0x604000084c40 h=--& v=--& NSView:0x60c000120b40.width == 0.5   (active)>",
    "<NSLayoutConstraint:0x60c0000822b0 H:|-(1)-[NSSearchField:0x100412290]   (active, names: '|':NSView:0x60c000120b40 )>",
    "<NSLayoutConstraint:0x60c000085f50 NSSearchField:0x100412290.trailing == NSView:0x60c000120b40.trailing   (active)>"
)

哪个有意义..显然,搜索字段前导/尾随锚点不能被-1偏移,如果我删除偏移量,则约束条件没有问题。

问题是我想要左/右偏移。必须有一种方法可以通过AutoLayout执行此操作,但我无法弄明白。有谁知道如何正确地做到这一点?

1 个答案:

答案 0 :(得分:1)

将分隔线拖到末尾与折叠不同。从api-docs返回最小可用大小并实现constrainMinCoordinate