I need to replicate the function of bringSubviewToFront: on the iPhone, but I am programming on the Mac. How can this be done?
This is Swift 3.0 solution:
extension NSView {
public func bringToFront() {
let superlayer = self.layer?.superlayer
self.layer?.removeFromSuperlayer()
superlayer?.addSublayer(self.layer!)
}
}
Pete Rossi's answer didn't work for me because I needed to pop the the view to front when dragging it with the mouse. However, along the same lines the following did work without killing the mouse:
CALayer* superlayer = [[view layer] superlayer];
[[view layer] removeFromSuperlayer];
[superlayer addSublayer:[view layer]];
Also, the following placed in a NSView subclass or category is pretty handy:
- (void) bringToFront {
CALayer* superlayer = [[self layer] superlayer];
[[self layer] removeFromSuperlayer];
[superlayer addSublayer:[self layer]];
}
Haven't actually tried this out - and there may be better ways to do it - but this should work:
NSView* superview = [view superview];
[view removeFromSuperview];
[superview addSubview:view];
This will move 'view' to the front of its siblings
also be sure to enable the layer for quartz rendering:
...
NSImageView *anImage = [[NSImageView alloc] initWithFrame:NSRectMake(0,0,512,512)];
[anImageView setWantsLayer:YES];
...
otherwise, your layer cannot be rendered correctly.
Sibling views that overlap can be hard to make work right in AppKit—it was completely unsupported for a long time. Consider making them CALayers instead. As a bonus, you may be able to reuse this code in your iOS version.
Pete Rossi's answer works, but remember to retain the view when you remove it from the superview.
You can add this in a category on NSView :
-(void)bringSubviewToFront:(NSView*)view
{
[view retain];
[view removeFromSuperview];
[self addSubview:view];
[view release];
}