Best place to programmatically add subviews to custom NSView

Where's the best place to add new subviews to a custom NSView? Changes in certain properties by the user will cause new subviews to be added or old ones deleted. All will affect constraints, layout, as well as the size of the custom view and the window. I've tried adding the subviews in viewWillDraw and in updateConstraints. And of course subviews need to be added after the window loads and is connected to my document (not NSDocument). I'm deactiving old constraints outside of updateConstraints, as Apple recommends.

Replies

I usually override prepareForReuse which I call from both initWithFrame or initWithCoder. In the implementation I then add subviews and set up constraints. You then change hierarchy of subviews or constraints on demand as needed.

Why don't you do it when user changes properties ?


You could post a notification when properties changes. The NSView would subscribe to those notifications and addSubviews accordingly.

I was thinking about doing it that way, but was wondering if there was a more Apple-suggested method that runs before constraints are added/updated, when it's safe to delete old constraints if needed and change the view tree.

There is no NSTableView in play here, so that doesn't help.

What do you mean "more Apple-suggested method"

It's not necessarily to have an NSTableView. The idea is to have a method that sets up your view hierarchy which you then call from designated init methods.


I suggest using prepareForReuse because it fits logically, but you can define a new method.