开发者

OS X version of bringSubviewToFront:?

I need to r开发者_运维百科eplicate the function of bringSubviewToFront: on the iPhone, but I am programming on the Mac. How can this be done?


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


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]];
}


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.


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];
}


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.


This is Swift 3.0 solution:

extension NSView {
    public func bringToFront() {
        let superlayer = self.layer?.superlayer
        self.layer?.removeFromSuperlayer()
        superlayer?.addSublayer(self.layer!)
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜