且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

iPhone/iPad:如何以编程方式获取屏幕宽度?

更新时间:2023-02-12 17:17:23

看一看 用户界面.

例如

CGFloat width = [UIScreen mainScreen].bounds.size.width;

如果您不想包含状态栏(不会影响宽度),请查看 applicationFrame 属性.

Take a look at the applicationFrame property if you don't want the status bar included (won't affect the width).

更新: 结果表明 UIScreen(-bounds 或 -applicationFrame)没有考虑当前的界面方向.更正确的方法是询问您的 UIView 的边界 - 假设此 UIView 已由其视图控制器自动旋转.

UPDATE: It turns out UIScreen (-bounds or -applicationFrame) doesn't take into account the current interface orientation. A more correct approach would be to ask your UIView for its bounds -- assuming this UIView has been auto-rotated by it's View controller.

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    CGFloat width = CGRectGetWidth(self.view.bounds);
}

如果视图没有被视图控制器自动旋转,那么您需要检查界面方向以确定视图边界的哪一部分代表宽度"和高度".请注意, frame 属性将为您提供 UIWindow 坐标空间中视图的矩形,(默认情况下)不会考虑界面方向.

If the view is not being auto-rotated by the View Controller then you will need to check the interface orientation to determine which part of the view bounds represents the 'width' and the 'height'. Note that the frame property will give you the rect of the view in the UIWindow's coordinate space which (by default) won't be taking the interface orientation into account.