Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding how subview.center = view.center 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:

SubView.center = view.center;

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

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

Setting subview.center is weird to me. subview.center 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?

like image 258
user1060500 Avatar asked Dec 27 '22 10:12

user1060500


1 Answers

To centre a subview inside a view. I think following code is correct.

Swift 3.0:

SubView.center = CGPoint(x: view.bounds.midX, y: view.bounds.midY );

Swift 2.2:

SubView.center = CGPointMake( CGRectGetMidX( view.bounds ), CGRectGetMidY( view.bounds ) );
like image 109
Satachito Avatar answered Feb 09 '23 01:02

Satachito