开发者

UIView setCenter problem

开发者 https://www.devze.com 2023-02-18 05:41 出处:网络
I\'m having a lot of trouble doing something very simple. I have a viewController and a subViewController, both with views loaded from nibs. For clarification the parent view is sized 1024 by 748 and

I'm having a lot of trouble doing something very simple. I have a viewController and a subViewController, both with views loaded from nibs. For clarification the parent view is sized 1024 by 748 and the subView is 640 by 480 in the nibs.

On the viewController's viewDidLoad I add the subViewController's view like so:

[self.view addSubview:self.subViewController.view];
NSLog(@"subview.frame:%@",NSStringFromCGRect(self.subViewController.view.frame));

The log outputs:

subview.frame:{{0, 0}, {640, 480}}

Then, just to test things out, I use setCenter to attempt to reposition the subview within the parent view at the same position like so:

CGPoint newCenter = CGPointMake(0,0);  //should stay at the same position..
[self.subViewController.view setCenter:newCenter];
NSLog(@"after changing center.subview.frame:%@",NSStringFromCGRect(self.subViewController.view.frame));

The log outputs:

after changing center. subview.frame:{{-320, -240}, {640, 480}}

Now I have a feeling that something might be getting screwed up in the nibs and am guessing it's something to do with the springs & struts / size & position options. I can only guess it's this because this is the feature I have least understanding of when it comes to IB.

Any other ideas as to what could be causing this issue? Do you guys have any tips in general on how to set up viewcontrollers' views in IB so that they are automatically positioned in alignment with other viewcontrollers' views? 开发者_如何学GoAnd after setting things up, is setCenter the correct way of moving them around dynamically?


The outputs are correct given what you are doing. The point (0,0) is the top-left corner. If you set the center of subview to this, then the top left corner of the subview will indeed be (-640/2, -480/2).

To get the top-left corners to align, use

[self.subViewController.view setCenter:CGPointMake(320.0,240.0)];


The problem is unclear. If you set the center to 0,0, then you should expect the frame origin to be -320, -240 as it appears to be. Perhaps you misunderstand CGRect? CGRect is made up of origin and size. Frame is a CGRect. Frame, size and center are all related, and changing frame changes size and center, and changing center changes frame.

0

精彩评论

暂无评论...
验证码 换一张
取 消