OS X version of bringSubviewToFront:?
Asked Answered
D

6

10

I need to replicate the function of bringSubviewToFront: on the iPhone, but I am programming on the Mac. How can this be done?

Digitalin answered 21/11, 2010 at 3:34 Comment(0)
D
9

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

Dagley answered 21/11, 2010 at 4:28 Comment(2)
Probably inefficient, but it accomplishes what I wanted, so thanks.Digitalin
It may be worth investigating using the setSubviews: method instead.Ligament
D
6

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]];
}
Daph answered 8/2, 2013 at 1:10 Comment(1)
I came looking for the solution to this and, barring a kerfuffle because my hosting view was not layer backed, this worked a treat. Thank you for sharing it.Havenot
P
1

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.

Pink answered 30/12, 2010 at 13:42 Comment(0)
B
1

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];
}
Blat answered 14/4, 2012 at 18:28 Comment(0)
K
0

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.

Khufu answered 21/11, 2010 at 5:40 Comment(0)
W
0

This is Swift 3.0 solution:

extension NSView {
    public func bringToFront() {
        let superlayer = self.layer?.superlayer
        self.layer?.removeFromSuperlayer()
        superlayer?.addSublayer(self.layer!)
    }
}
Wafture answered 3/12, 2017 at 16:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.