【问题标题】:Why is self.view height and width different than a sub view's height and width?为什么 self.view 的高度和宽度与子视图的高度和宽度不同?
【发布时间】:2012-11-05 09:09:37
【问题描述】:

无论方向如何,主屏幕和 self.view 始终保持相同的宽度和高度尺寸背后的逻辑是什么(即使 self.view 确实重新调整大小以适合当前设备方向),而self.view 的 sub-View 在设备方向改变时返回修改后的宽高尺寸?

NSLog(@"screen bounds w: %f, h: %f", [[UIScreen mainScreen] bounds].size.width,[[UIScreen mainScreen] bounds].size.height );

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

NSLog(@"myView frame w: %f, h: %f", _myView.frame.size.width, _myView.frame.size.height );

日志输出纵向

2012-11-05 16:15:11.152 test[2807:11303] screen bounds w: 320.000000, h: 480.000000
2012-11-05 16:15:11.153 test[2807:11303] self.view frame w: 320.000000, h: 460.000000
2012-11-05 16:15:11.153 test[2807:11303] myView frame w: 320.000000, h: 460.000000

日志输出景观

2012-11-05 16:14:38.800 test[2807:11303] screen bounds w: 320.000000, h: 480.000000
2012-11-05 16:14:38.801 test[2807:11303] self.view frame w: 300.000000, h: 480.000000
2012-11-05 16:14:38.801 test[2807:11303] myView frame w: 480.000000, h: 300.000000

【问题讨论】:

    标签: objective-c ios xcode views dimensions


    【解决方案1】:

    实际上它不仅仅是自动调整大小的蒙版。所以当你改变设备的方向时,屏幕的物理特性保持不变。如果您将视图设置为自动旋转,则会为您转换宽度和高度。因此,当要求具有翻译视图的屏幕尺寸时,它的 imp。让您根据self.view.centerself.view.bounds 而不是self.view.frame 进行计算。

    【讨论】:

      【解决方案2】:

      对于 iPhone,[UIScreen mainScreen] 始终是 320w480h568h 对于 iPhone5)。
      [UIScreen mainScreen] 的尺寸被用于纵向。

      根据您的NSLog,设备状态栏在您的应用中可见。因此,您在横向有300h,在纵向有460h

      【讨论】:

        【解决方案3】:

        这取决于为您的子视图设置的 autoSizingMask 属性。

        我推测您没有使用 iOS 6.0 的AutoLayout 功能。如果你这样做了,那么你需要更多地查看 iOS 6.0 中的约束设置。

        默认情况下,您的视图的自动调整大小蒙版是“缩放以填充”,请参见附图。您可以根据您的要求为您的子视图设置相同的值。在 Apple 文档中查看更多关于 Struts 和 Springs 的信息。

        如果自动调整大小不符合您的要求,那么您将需要实施自定义方法来根据方向更改布局视图。如下所示;

        - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
            [UIView animateWithDuration:duration animations:^{
                [self layoutForOrientation:toInterfaceOrientation];
            }];
        }
        
        #pragma mark - Layout views
        
        - (void)layoutForOrientation:(UIInterfaceOrientation)orientation {
            if (UIInterfaceOrientationIsPortrait(orientation))
                [self layoutPortraitViews];
            else
                [self layoutLandscapViews];
        }
        
        - (void)layoutLandscapViews {
            // Layout your landscape views
        }
        
        - (void)layoutPortraitViews {
           // Layout your portrait views
        }
        

        【讨论】:

          最近更新 更多