How to align a subview to the center of a parent NSView

Swift 5 @d11wtq's answer

    let x = (parentView.bounds.width - subviewWidth) * 0.5
    let y = (parentView.bounds.height - subviewHeight) * 0.5
    let f = CGRect(x: x, y: y, width: subviewWidth, height: subviewHeight)
    let subview = NSView(frame: f)
    subview.autoresizingMask = [.minXMargin, .maxXMargin, .minYMargin, .maxYMargin ]

I'm not sure if this is the best way to do it, but I just do simple math when I want to center a subview inside its parent.

You need to set all the margins to be auto-resizable if you want it to stay centered.

[subview setFrameOrigin:NSMakePoint(
  round((NSWidth([parentView bounds]) - NSWidth([subview frame])) / 2),
  round((NSHeight([parentView bounds]) - NSHeight([subview frame])) / 2)
)];
[subview setAutoresizingMask:NSViewMinXMargin | NSViewMaxXMargin | NSViewMinYMargin | NSViewMaxYMargin];

This is just calculating the margins required to get a centered origin.

If you need the centered frame before you invoke initWithFrame: then just use the above logic to compute the frame origin values.

Tags:

Macos

Cocoa