12

I need to get the center point of a NSView in the form of a CGPoint, how can I achieve this? I am basically looking for the equivalent of the UIKit, UIView.center

Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
foobar5512
  • 2,470
  • 5
  • 36
  • 52

3 Answers3

19

A simple and easy to read way is:

CGPointMake(NSMidX(myView.frame), NSMidY(myView.frame))

I would suggest making this code, a category on NSView with a read only property named center.

Kaunteya
  • 3,107
  • 1
  • 35
  • 66
lmirosevic
  • 15,787
  • 13
  • 70
  • 116
  • 2
    +1 for NSMidX, wouldn't recommend naming it 'center' though. There already is a -(void)center method on NSWindow so might resolve wrong, and it's a fairly obvious name so Apple might use it as well, but maybe implement it slightly differently and things will break. – uliwitness Feb 28 '15 at 11:18
  • @uliwitness NSWindow does not inherit from NSView, so that shouldn't be an issue. – aleclarson Mar 02 '19 at 17:27
  • `NSWindow` doesn't inherit from `NSView`, but nobody's stopping Apple from adding a `-center` method to NSView in the future, and then you get *really* interesting behavior. So when adding categories to Apple classes, it's always a good idea to either use a prefix like `foo_center`, or to at least stay away from the obvious names. – uliwitness Mar 13 '19 at 13:16
16

This code will get you that CGPoint:

CGPointMake((myView.frame.origin.x + (myView.frame.size.width / 2)),
            (myView.frame.origin.y + (myView.frame.size.height / 2)))
Regan
  • 1,487
  • 2
  • 28
  • 43
1

To get an NSPoint of the center, you can just get the x-coordinate of the origin and add (width/2), and get the y-coordinate of the origin and add (height/2). Then you can convert it into a CGPoint.

jburns20
  • 3,147
  • 2
  • 26
  • 32