Skip to content
Ken Harris edited this page Dec 22, 2017 · 5 revisions

NSView is the base "thing you see on the screen".

What

There seems to be an art to picking how to divide up a UI into views, and how to split the responsibilities between NSView and NSViewController. The general rules I've got so far are:

  • Views should be reusable. Will you want to use something again? Make it a view.
  • Views should be dumb. Think "NSButton": you get a target/action, but there's no business logic anywhere.

There are very few hard-and-fast rules about what should or shouldn't be a view. Some points:

  • In 10.13 (section "Drag & Drop Auto Image Scaling"), drag-n-drop auto-scaling happens when you drag an object out of its source view.
  • Many newer classes (like NSCollectionView and NSTabViewController) are built around NSViewControllers, so you'll need to use them if you want to take advantage of these.

In some places, you'll find the option to use NSCell. It's not marked "deprecated" in the API docs, but the release notes say there is a "Gradual deprecation of NSCell". There are a few places where NSCell is still required, like setting the lineBreakMode on NSTextField.

How

Rule of thumb: an NSView subclass should override draw(:), or have subviews, but not both. Yes, it's well-defined how things are drawn when you've got both, but it's often not what you want, and you can't re-use views as easily, and it's just a pain.

  • One exception: NSTableCellView. You might have 100 on screen at once, so performance matters. You might not want to run autolayout 100 times. I'm happy to do simple drawing in a table cell, if it avoids extra layout.
Clone this wiki locally