3

我想在设备旋转时进行一些布局更改。所以我实现- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration了方法来完成这项工作。但是我意识到当这个方法被调用时 self.view.frame 和 self.view.bounds 是不同的。self.view.bounds.size 是正确的,而 self.view.frame.size 似乎仍然没有旋转。

例如,我创建了一个空的 singleView 项目并实现了如下方法:

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    NSLog(@"willAnimateRotationToInterfaceOrientation");

    NSLog(@"self.view.bounds.size width:%f height:%f ",self.view.bounds.size.width,self.view.bounds.size.height);
    NSLog(@"self.view.frame.size width:%f height:%f",self.view.frame.size.width,self.view.frame.size.height);

}

当设备从纵向旋转到横向时。输出如下:

2013-06-11 11:57:46.959 viewDemo[95658:707] willAnimateRotationToInterfaceOrientation
2013-06-11 11:57:46.961 viewDemo[95658:707] self.view.bounds.size width:1024.000000 height:748.000000 
2013-06-11 11:57:46.961 viewDemo[95658:707] self.view.frame.size width:748.000000 height:1024.000000

我想知道为什么这些尺寸不同?他们不应该总是一样的吗?什么时候选择使用哪一个?

任何帮助将不胜感激。

4

4 回答 4

5

“tc”的答案。,目前已被接受。从那个答案复制几行到这里。

因此,“框架”是相对于父视图的,在这种情况下是 UIWindow。旋转设备时,窗口不旋转;视图控制器的视图确实如此。从窗口的角度来看,一切都有效地处于纵向模式。这就是为什么即使设备旋转到横向后,self.view.frame 也不会改变。

您应该使用self.view.bounds它来执行任何计算,因为它会为您提供与设备方向无关的正确值。

于 2013-06-11T05:35:40.207 回答
2

我想知道为什么这些值不同?他们不应该总是一样的吗?
UIView的边界是矩形,表示为相对于其自身坐标系 (0,0) 的位置 (x, y) 和大小 (width, height)

UIView的frame是一个矩形,表示为相对于它所在的 superview的位置 (x, y) 和大小 (width, height) 。

在边界的情况下,x 和 y 坐标位于 0,0,因为这些坐标是相对于视图本身的。但是,框架 x 和 y 坐标是相对于视图在父视图中的位置

什么时候选择使用哪一个?
希望这有助于澄清每个属性可能被使用的情况。
UIView的frame,bounds,center,origin,什么时候用什么?

于 2013-06-11T05:21:22.657 回答
0

请注意,当模拟器旋转时,frame.size 不等于 bounds.size

参考这一个UIView 框架,边界和中心

于 2013-06-11T04:07:26.870 回答
0

只需使用方法 did(大小是新的)不会(大小与父控制器中的相同)

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];

    [halfView setFrame:CGRectMake(0, 0, self.view.bounds.size.width, 120)];
    NSLog(@"willAnimateRotationToInterfaceOrientation");
    NSLog(@"self.view.bounds.size width:%f height:%f ",self.view.bounds.size.width,self.view.bounds.size.height);
    NSLog(@"self.view.frame.size width:%f height:%f",self.view.frame.size.width,self.view.frame.size.height);

}
于 2016-02-29T10:17:25.343 回答