在基于视图的NSTableView中自动布局



我有一个创建行的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实际上是一个稍微小一点的视图,以伪造行之间的"间隙"和与表视图边缘的间距。。

如果有人偶然发现了这一点。。事实证明,NSTableCellView在没有最小大小的情况下有点不稳定——在垂直约束上添加(>=10)就解决了这个问题。。

最新更新