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?
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 ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With