Search code examples
nsviewnsscrollview

Notification when custom NSView has been added to a NSScrollView


Following on this question (Custom NSView embedded in NSSscrollView), when my custom view is embedded in a NSScrollView using IB, I can detect this in awakeFromNib method and perform the required initialization (I have to setup some scroll notifications).
My problem is when by custom view is added to a NSScrollView from code, setting the scrollview's documentView property. In this scenario is my custom view notified in any way (some NSView method that is called and I can override) or I have to perform my initialization explicitly after my view has been added to the scroll view?


Solution

  • The documentView of the scroll view is a subview of this scroll view and NSView has lots of usefull methods. In the chapter "Managing the View Hierarchy":

    viewDidMoveToSuperview

    Informs the view that its superview has changed (possibly to nil).

    viewDidMoveToWindow

    Informs the view that it has been added to a new view hierarchy.

    When the view is added to a superview, viewDidMoveToSuperview is called. But the view could already be inside a view (in a XIB or in code) and this superview could be added to a scroll view. viewDidMoveToWindow is called when the view has been added to or removed from a view hierarchy.