0

I have a NSTableView that holds a name to all of my NSImageView's, and depending on the order that the NSImageViews were added, the last one would be in the front.

But in the case that I want the user to be able to bring a NSImageViews in front of another, how would I do that?

Thanks in advance.

2 Answers2

2

As explained on the NSView reference page, the z-order of a view's subview is given by their oder in the view's subviews array. You can insert a new subview relative to the others using -addSubview:positioned:relativeTo:, and you can reorder the existing subviews by getting the subviews property, reordering the views therein as you like, and then calling -setSubviews: to set the new order.

Specifically, the docs say:

The order of the subviews may be considered as being back-to-front, but this does not imply invalidation and drawing behavior.

Caleb
  • 124,013
  • 19
  • 183
  • 272
1

What you are asking about, I think, is how to control the z-order of views.

For historical performance reasons this is not well supported in AppKit (unlike UIKit in iOS), since until somewhat recently you couldn't actually have sibling views that overlap.

A common approach to this (on recent OS X releases) is to use Core Animation (in particular, CALayer) which does support z-ordering natively, but this is probably overkill for what you need (and in any event is going to have a learning curve for you).

What are you actually trying to do? Are these images (image views) precisely on top of one another? If so, the easiest (and much better performing) approach is to have a single NSImageView and to just send -setImage:... to it to change the displayed image.

Conrad Shultz
  • 8,748
  • 2
  • 31
  • 33
  • I'm dragging and dropping X amount of images onto the screen, so they're all showing at once. The application I'm building is creating a scene, so the user may want some images behind or in front of other images without having to delete the image and add it in again. Does that make sense? – ObjectiveC-InLearning Jun 20 '12 at 00:54
  • A simple example, I have a NSImageView directly overlapping another NSImageView, there's no easy way to get the one behind it to jump to the front? I'll look into CALayer if not. – ObjectiveC-InLearning Jun 20 '12 at 00:57
  • @ObjectiveC-InLearning I believe you can accomplish what you want with `-addSubview:positioned:relativeTo:` to insert a view in the right z-order, but this is going to be cumbersome and potentially fragile (as @Caleb just noted). If you are going to have a lot of images, you will eventually probably need to look at using a layer-backed view and associated `CALayer` operations. – Conrad Shultz Jun 20 '12 at 01:00