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
Asked
Active
Viewed 7,995 times
3 Answers
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@user668518: So make one. It'll be better anyway to use your property/method everywhere you need the center than to copy and paste the coordinate-math code. – Peter Hosey Jul 04 '11 at 03:03
-
-
This does not take `CALayer#transform` into account, like `UIView#center` does. – aleclarson Mar 02 '19 at 17:30
-
But this is correct only when the nsview wasn't rotated. After rotation origin is moved and center point your above calculations are incorrect. – fillky Jun 05 '12 at 09:46
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