Move a subview to front…


I’m sure there is a simple way to do this, but I just can’t find it. I have a content view with a certain number of custom subviews (DragView), which allow to be dragged.

When I click on a dragView, it shows the correct selection outline, then I can drag it around. The problem is, this dragView will pass “under” other dragViews. So the solution should be to move the selected dragView on top of the superview’s subviews. But how?

subviews are in a NSArray, so I can just remove the view and add it again (no possible index changes).

NSView* copy = _superview
[self removeFromSuperview];
[copy addSubview: self];

This is OK for the view, but I loose the mouse.

Any ideas?

Well, I cannot say for the mouse that stops responding, but the change I would make is switch from NSArray to NSMutableArray, and then move the view to index 0.

But I’m curious, why not add the view as the first one in the array at launch already? I don’t have the context of course, but this is something I would do to try and fix this…

Model: MacBookPro8,2
Browser: Safari 534.51.22
Operating System: Mac OS X (10.7)

Hi leonsimard,

Because there may be, say, 10 DragViews into the superview, and I can’t guess which one the use is going to select and drag.

I tried this, it works, but I just wonder if it is elegant, or even if it reveals a bad design :

I don’t have a ton of experience with mouse events, but the logic looks good to me.

I would cast the NSMutableArray as NSArray before sending it to your subview, like this:

[_superview setSubviews:(NSArray*)newContents];

. would kill alerts if any, and potential problems because setSubviews: expects and NSArray.

Again, not an expert on mouse events, maybe someone else will have something better to share.

Good luck!

Model: MacBookPro8,2
Browser: Safari 534.51.22
Operating System: Mac OS X (10.7)

And also put a test early on to check if you have at least 2 objects in your array. Unless you are certain some other way that there is at least 2 from launch to quit. Again, not having the context.

Thanks a lot. Didn’t get any alert but. a bit of coercion doesn’t hurt.

The context indeed. it’s a Core Data application, so it would be certainly off the topic to post the whole stuff (a custom view to represent an entity, with a lot of bindings and crossed links):slight_smile:

Are you using iOS? :confused:

No. My apps do not require a lot of checking for mouse events. They are mostly utilities doing a specific job. Not saying I won’t ever need to use that, but so far the need has not arisen. :slight_smile:

Hello fiz.

If it is so, that the index of your views are describing the front to back layering of your views, then you shouldn’t just exchange the position, but the former element at index 1, should become the element at index 2 and so on until you have replaced the current dragviews former position.

That is at least what I figure should be the natural way of reordering the dragviews.