Wednesday, 2 January 2013

NSScrollView and CoreLayout

Recently I've been trying to convert an application to use CoreLayout and one of the problems I ran into was with getting content to correctly fill an NSScrollView.

I have an NSView subclass which lays out its subviews in a vertical list using constraints and while the height of the layout is obviously dependent on the combined height of the subviews (plus spacing) the children don't have any intrinsic width and so are dependent on the width the parent class gave them. Ultimately, this was the width which the NSScrollView gives, but the problem was that the NSScrollView wanted to give them 0 width.

The solution I came up with is to add a constraint to the NSClipView which sits inbetween the NSScrollView and my layout view like so:

[_layout setTranslatesAutoresizingMaskIntoConstraints:NO];
[_scrollView setDocumentView:_layout];

NSClipView *clipView = [_scrollView contentView];
NSDictionary *viewsDict = @{@"layout":_layout};

// Add our new constraint that will fix the sides of _layout
// to the sides of its parent, which in this case is clipView
[clipView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[layout]|" options:0 metrics:nil views:viewsDict]];

It was surprisingly easy once I realised that I could add constraints like this. Hopefully this will help some people if they run into issues like this.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.