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

时间:2010-09-07 00:54:08

标签: iphone objective-c cocoa-touch ipad

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

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

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

6 个答案:

答案 0 :(得分:195)

看看UIScreen

例如

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

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

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

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

如果View Controller没有自动旋转视图,那么您需要检查界面方向以确定视图边界的哪个部分代表'width'和'height'。请注意,frame属性将为您提供UIWindow坐标空间中视图的矩形(默认情况下)将不考虑界面方向。

答案 1 :(得分:11)

CGRect screen = [[UIScreen mainScreen] bounds];
CGFloat width = CGRectGetWidth(screen);
//Bonus height.
CGFloat height = CGRectGetHeight(screen);

答案 2 :(得分: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];

答案 3 :(得分:0)

从iOS 9.0开始,无法可靠地获得方向。这是我用于仅为肖像模式设计的应用程序的代码,因此如果应用程序以横向模式打开,它仍然是准确的:

screenHeight = [[UIScreen mainScreen] bounds].size.height;
screenWidth = [[UIScreen mainScreen] bounds].size.width;
if (screenWidth > screenHeight) {
    float tempHeight = screenWidth;
    screenWidth = screenHeight;
    screenHeight = tempHeight;
}

答案 4 :(得分:0)

使用此代码可以提供帮助

[[UIScreen mainScreen] bounds].size.height
[[UIScreen mainScreen] bounds].size.width

答案 5 :(得分:0)

使用:

NSLog(@"%f",[[UIScreen mainScreen] bounds].size.width) ;