How do I make an NSView move to the front of all NSViews

前端 未结 7 1043
既然无缘
既然无缘 2020-12-28 12:47

I have a super view, which has 2 subviews. These subviews are overlapped.

Whenever i choose a view from a menu, corresponding view should become the front view and h

相关标签:
7条回答
  • 2020-12-28 13:11

    You can achieve this by just adding the view again; it will not create another instance of it.

    [self addSubview:viewToBeMadeForemost];
    

    You can Log the number of subviews before and after this line of code is executed.

    0 讨论(0)
  • 2020-12-28 13:17

    using @Dalmazio's answer in a Swift 4 category that mimics the equivalent UIView method gives the following:

    extension NSView {
    
        func bringSubviewToFront(_ view: NSView) {
                var theView = view
                self.sortSubviews({(viewA,viewB,rawPointer) in
                    let view = rawPointer?.load(as: NSView.self)
    
                    switch view {
                    case viewA:
                        return ComparisonResult.orderedDescending
                    case viewB:
                        return ComparisonResult.orderedAscending
                    default:
                        return ComparisonResult.orderedSame
                    }
                }, context: &theView)
        }
    
    }
    

    so, to bring subView to the front in containerView

    containerView.bringSubviewToFront(subView)
    

    unlike solutions which remove and re-add the view, this keeps constraints unchanged

    0 讨论(0)
  • 2020-12-28 13:27

    Below given code should work fine..

        NSMutableArray *subvies = [NSMutableArray arrayWithArray:[self subviews]];//Get all subviews..
    
        [viewToBeMadeForemost retain]; //Retain the view to be made top view..
    
        [subvies removeObject:viewToBeMadeForemost];//remove it from array
    
        [subvies addObject:viewToBeMadeForemost];//add as last item
    
        [self setSubviews:subvies];//set the new array..
    
    0 讨论(0)
  • 2020-12-28 13:28

    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.

    0 讨论(0)
  • 2020-12-28 13:32

    I was able to get this to work without calling removeFromSuperView

    // pop to top
    [self addSubview:viewToBeMadeForemost positioned:NSWindowAbove relativeTo:nil];
    
    0 讨论(0)
  • 2020-12-28 13:35

    You might try this:

    [viewToBeMadeFirst.window makeKeyAndOrderFront:nil];
    
    0 讨论(0)
提交回复
热议问题