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

for*_*yez 81 iphone cocoa-touch objective-c ipad

嗨,我想知道是否有办法以编程方式获得宽度.

我正在寻找足以容纳iphone 3gs,iphone 4,ipad的东西.此外,宽度应根据设备是纵向还是横向(对于ipad)而改变.

谁知道怎么做?我一直在寻找...谢谢!

Ala*_*ers 201

看看UIScreen.

例如.

CGFloat width = [UIScreen mainScreen].bounds.size.width;
Run Code Online (Sandbox Code Playgroud)

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

更新:事实证明,UIScreen(-bounds或-applicationFrame)没有考虑当前的界面方向.更正确的方法是询问你的UIView的界限 - 假设这个UIView已被它的View控制器自动旋转.

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    CGFloat width = CGRectGetWidth(self.view.bounds);
}
Run Code Online (Sandbox Code Playgroud)

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

  • 对于那些可能偶然发现这个旧帖子的人,我发现self.view.bounds只有从didRotateFromInterfaceOrientation开始才完全准确.如果视图以其初始目标方向显示(如IB中所指定),它在viewDidLoad和viewWillAppear中也将是准确的.如果视图以不同的方向显示然后是目标,则在didRotateFromInterfaceOrientation和view.bounds将不正确之前调用viewDidLoad(和viewWillAppear) (5认同)
  • 实际上,当ipad面向横向时,这不起作用..即,如果我的模拟器正在运行横向,那么它仍然返回768(而不是1024).你认为我应该有一个if语句来检查那种情况下的方向还是有更好的方法来获得宽度? (3认同)

小智 11

CGRect screen = [[UIScreen mainScreen] bounds];
CGFloat width = CGRectGetWidth(screen);
//Bonus height.
CGFloat height = CGRectGetHeight(screen);
Run Code Online (Sandbox Code Playgroud)

  • 不考虑方向 (10认同)

mem*_*ons 6

这可以在3行代码中完成:

// grab the window frame and adjust it for orientation
UIView *rootView = [[[UIApplication sharedApplication] keyWindow] 
                                   rootViewController].view;
CGRect originalFrame = [[UIScreen mainScreen] bounds];
CGRect adjustedFrame = [rootView convertRect:originalFrame fromView:nil];
Run Code Online (Sandbox Code Playgroud)

  • 这很接近,但如果正在显示UIAlertView,它将是关键窗口,其rootViewController属性将为nil (3认同)