How do I make an NSView move to the front of all NSViews
Here's another way to accomplish this that's a bit more clear and succinct:
[viewToBeMadeForemost removeFromSuperview];
[self addSubview:viewToBeMadeForemost positioned:NSWindowAbove relativeTo:nil];
Per the documentation for this method, when you use relativeTo:nil
the view is added above (or below, with NSWindowBelow
) all of its siblings.
Another way is to use NSView's sortSubviewsUsingFunction:context: method to re-order a collection of sibling views to your liking. For example, define your comparison function:
static NSComparisonResult myCustomViewAboveSiblingViewsComparator( NSView * view1, NSView * view2, void * context )
{
if ([view1 isKindOfClass:[MyCustomView class]])
return NSOrderedDescending;
else if ([view2 isKindOfClass:[MyCustomView class]])
return NSOrderedAscending;
return NSOrderedSame;
}
Then when you want to ensure your custom view remains above all sibling views, send this message to your custom view's superview:
[[myCustomView superview] sortSubviewsUsingFunction:myCustomViewAboveSiblingViewsComparator context:NULL];
Alternatively, you can move this code to the superview itself, and send the message sortSubviewsUsingFunction:context: to self instead.