Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change NSView subviews order

I'm working at a custom control that presents different handles. I want to be sure that the selected handle has a Z-index grater then the others handles.

Is there a way to swap view order? I found this function sortSubviewsUsingFunction:context: but i can't understand whether this is the right solution.

like image 664
MatterGoal Avatar asked Jul 03 '12 13:07

MatterGoal


2 Answers

Cocoa introduced a new API in macOS 10.0.
It's similar to iOS, you can pass another view to be displayed below or above.

[self.view addSubview:myView positioned:NSWindowBelow relativeTo:myViewInBackground];

Checkout the documentation; in my experience NSWindowBelow and NSWindowAbove seemed reversed though.

like image 174
Axel Guilmin Avatar answered Oct 18 '22 14:10

Axel Guilmin


It is pretty simple, you can use a function that compare 2 subviews to reorder them. Here a simple solution based on view's tag:

[mainView sortSubviewsUsingFunction:(NSComparisonResult (*)(id, id, void*))compareViews context:nil];

...

NSComparisonResult compareViews(id firstView, id secondView, void *context) { 
    int firstTag = [firstView tag];
    int secondTag = [secondView tag];

    if (firstTag == secondTag) {
        return NSOrderedSame;
    } else {
        if (firstTag < secondTag) {
            return NSOrderedAscending;
        } else { 
            return NSOrderedDescending;
        }
    }
}
like image 6
Marco Pace Avatar answered Oct 18 '22 14:10

Marco Pace