My UIViewController is "lying" about its center property

I ask my ViewController its view.center property and draw a new UIView that centers around this "center" ... I get (160, 250) as an answer. but when the new UIView draws it below the center ... So I wonder who gives me this information and what is it related to? Obviously, the view center refers to the WINDOW if you take into account the height of the state of 20px of the status bar. which will push the center of the view down 10 pixels. but when drawing myView it looks like a relation to ViewController.view, not a window, so it appears 20 pixels below the center ...

I would expect the ViewController to give me its center (160, 230) so that I can draw it in the center ... do I need to manually register the status bar and subtract 20 from a height each time? or is there some kind of translation of the space of vision that I am missing? From ViewController.m:

- (void)setUpMyView {
// Create my view

MyView *aView = [[MyView alloc] init];
self.myView = aView;
[aView release];
myView.center = self.view.center;
NSLog(@"CenterX: %f, Y: %f", self.view.center.x, self.view.center.y);
CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI_2);
myView.transform = transform;

[self.view addSubview:myView];

}

Console

: CenterX: 160.000000, Y: 250.000000

+3
source share
3 answers

This is not a "lie" in fact, it gives you an answer in a different coordinate system.

, parent. self.view parent - , (160, 250), . myView parent self.view, . 20 , .

self.myView . .

1) bounds, CGRect, :

myView.center = CGPointMake(self.view.bounds.size.width / 2,
                            self.view.bounds.size.height / 2);

2) UIView convertPoint:fromView: self.view:

// Pass nil as the source view to convert from the window coordinate system
myView.center = [self.view convertPoint:self.view.center fromView:nil];
+10

, Subview, .

MyView *aView = [[MyView alloc] init];
self.myView = aView;
[aView release];
[self.view addSubview:myView]; // add it to the subview first before asking center.
myView.center = self.view.center;
NSLog(@"CenterX: %f, Y: %f", self.view.center.x, self.view.center.y);
CGAffineTransform transform = CGAffineTransformMakeRotation(M_PI_2);
myView.transform = transform;
0

, . !

iPhone 20 , , . .

0

Source: https://habr.com/ru/post/1711703/


All Articles