【问题标题】:Autolayout inside a view-based NSTableView基于视图的 NSTableView 中的自动布局
【发布时间】:2014-02-26 20:15:03
【问题描述】:

我有一个创建行的 NSTableView(基于视图);

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    TaskTableCellView *tableCellView = [[TaskTableCellView alloc] init];
    return tableCellView;
}

-(void) tableView:(NSTableView *)tableView didAddRowView:(NSTableRowView *)rowView forRow:(NSInteger)row {
    NSView *view = [rowView viewAtColumn:0];
    [view setTranslatesAutoresizingMaskIntoConstraints:NO];
    NSDictionary *views = NSDictionaryOfVariableBindings(view);
    [tableView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[view]|" options:0 metrics:nil views:views]];
    [tableView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view]|" options:0 metrics:nil views:views]];
}

- (CGFloat)tableView:(NSTableView *)tableView heightOfRow:(NSInteger)row {
    return 20;
}

这一行创建了一些子视图并分配了一些约束;

- (void)layout {
    [super layout];
    ViewWithBackground *viewWithBackground = [[ViewWithBackground alloc] init];
    viewWithBackground.backgroundColor = [NSColor greenColor];
    [self addSubview:viewWithBackground];

    [viewWithBackground setTranslatesAutoresizingMaskIntoConstraints:NO];
    NSDictionary *views = NSDictionaryOfVariableBindings(viewWithBackground);
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[viewWithBackground]|"
                                                                 options:0
                                                                 metrics:nil
                                                                   views:views]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[viewWithBackground]|"
                                                                 options:0
                                                                 metrics:nil
                                                                   views:views]];

    [viewWithBackground setContentHuggingPriority:200 forOrientation:NSLayoutConstraintOrientationVertical];
    [viewWithBackground setContentHuggingPriority:200 forOrientation:NSLayoutConstraintOrientationHorizontal];
}


- (void)drawRect:(NSRect)dirtyRect {
    [[NSColor redColor] set];
    NSRectFill(dirtyRect);
    [super drawRect:dirtyRect];
}

当我真正尝试编辑约束时,乐趣就开始了。viewWithBackground 只是一个设置它的背景的空 NSView。当约束为 |[viewWithBackground]|对于水平和垂直,我得到了预期的结果——绿色行。当我将其更改为最基本的 |-[viewWithBackground]-| 时,我得到了一个绝对出乎意料的结果——红色的行,没有我的绿色视图的迹象!

我应该在这里采取一些额外的步骤吗?我的目标是让我的 viewWithBackground 实际上是一个稍小的视图,以伪造行之间的“间隙”以及与表格视图边缘的间距..

【问题讨论】:

    标签: cocoa nstableview nstableviewcell nstablecellview


    【解决方案1】:

    万一有人偶然发现这一点。事实证明,没有最小尺寸的 NSTableCellView 有点不稳定——在垂直约束上添加 (>=10) 可以解决这个问题。

    【讨论】: