user1060500 user1060500 - 1 year ago 51
Objective-C Question

Understanding how = works and why the getter and setter do different things

I am seeing a lot of code that explains how to centre a subview inside a view. The code examples typically go like this: =;

Could someone explain to me how this works? I just don't get it.

gives the center point of the view. For example width is 100, height is 100, it will return (50,50). I get it.

is weird to me.
will return the center point of the subview. Somehow, setting it to (50,50) will position the subview within it's parent to coordinates of 50/50. But then accessing this property will return let's say (25,25) if the subview itself was width of 50 and height of 50.

Undestand what I mean? The concept here is weird to me as the setter and getter are doing different functions.

If someone could explain this please do. Or, if I am way off base I would like to know that too. I am new to iOS dev.

If I am correct and this is really the way it works, would you not consider this an anti-pattern. Certainly within .NET something like this would be an anti-pattern. Maybe not for Obj-C?

Answer Source

So when setting it, it is setting it inside it's superview. When getting the subviews center it gives you the actual views center.

So half of 50 is 25, hence 25,25. You are wanting the subview's center not its parent's center so there is no reason for it to return its parent's center coordinates, just its own.

To be a bit more technical it has to related to Frame and Bounds of a view (the getter is getting the center by using the view's bounds and the setter is using the view's frame). Here is a link that describes what those are and how they are different.