In AppKit (or UIKit) projects where I’ve decided to implement user interfaces strictly in code, rather than through storyboards or xibs, it gets tiresome to repeatedly type the following code:

let view = NSView(frame: .zero)
view.translatesAutoresizingMaskIntoConstraints = false

Here’s a little snippet I’ve been using to cut down on this somewhat:

extension NSView {
  static func autolayoutable() -> Self {
	let view = Self(frame: .zero)
	view.translatesAutoresizingMaskIntoConstraints = false
	return view

// Example usage when creating an NSTableView
let tableView = NSTableView.autolayoutable()

This works for almost all views I create but occasionally I want to use some of the convenience initializers for NSButton or NSTextView like labelWithString. In those cases, I don’t use the method above, I just disable autosizing manually.