OS X version of bringSubviewToFront:?

前端 未结 6 617
我在风中等你
我在风中等你 2021-02-08 19:07

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

相关标签:
6条回答
  • 2021-02-08 19:22

    This is Swift 3.0 solution:

    extension NSView {
        public func bringToFront() {
            let superlayer = self.layer?.superlayer
            self.layer?.removeFromSuperlayer()
            superlayer?.addSublayer(self.layer!)
        }
    }
    
    0 讨论(0)
  • 2021-02-08 19:26

    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]];
    }
    
    0 讨论(0)
  • 2021-02-08 19:33

    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

    0 讨论(0)
  • 2021-02-08 19:33

    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.

    0 讨论(0)
  • 2021-02-08 19:36

    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.

    0 讨论(0)
  • 2021-02-08 19:39

    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];
    }
    
    0 讨论(0)
提交回复
热议问题