在iOS中如何获得屏幕的尺寸?
目前,我使用:
lCurrentWidth = self.view.frame.size.width;
lCurrentHeight = self.view.frame.size.height;
在viewWillAppear:和willAnimateRotationToInterfaceOrientation:duration:
这是我第一次看到整个屏幕的大小。第二次我得到的屏幕减去导航栏。
在iOS中如何获得屏幕的尺寸?
目前,我使用:
lCurrentWidth = self.view.frame.size.width;
lCurrentHeight = self.view.frame.size.height;
在viewWillAppear:和willAnimateRotationToInterfaceOrientation:duration:
这是我第一次看到整个屏幕的大小。第二次我得到的屏幕减去导航栏。
当前回答
CGFloat宽度= [[UIScreen mainScreen] bounds].size.width; CGFloat height = [[UIScreen mainScreen]bounds].size.height;
其他回答
这里我已经更新了swift 3
applicationFrame已从iOS 9弃用
在swift 3中,他们已经删除了(),他们已经改变了一些命名惯例,你可以参考这里的链接
func windowHeight() -> CGFloat {
return UIScreen.main.bounds.size.height
}
func windowWidth() -> CGFloat {
return UIScreen.main.bounds.size.width
}
我以前用过这些方便的方法:
- (CGRect)getScreenFrameForCurrentOrientation {
return [self getScreenFrameForOrientation:[UIApplication sharedApplication].statusBarOrientation];
}
- (CGRect)getScreenFrameForOrientation:(UIInterfaceOrientation)orientation {
CGRect fullScreenRect = [[UIScreen mainScreen] bounds];
// implicitly in Portrait orientation.
if (UIInterfaceOrientationIsLandscape(orientation)) {
CGRect temp = CGRectZero;
temp.size.width = fullScreenRect.size.height;
temp.size.height = fullScreenRect.size.width;
fullScreenRect = temp;
}
if (![[UIApplication sharedApplication] statusBarHidden]) {
CGFloat statusBarHeight = 20; // Needs a better solution, FYI statusBarFrame reports wrong in some cases..
fullScreenRect.size.height -= statusBarHeight;
}
return fullScreenRect;
}
对于iPad分割窗口,[[UIScreen mainScreen] bounds]不起作用,使用[UIApplication sharedApplication].delegate.window.bounds代替。
注意,[UIScreen mainScreen]包含状态栏,如果你想检索你的应用程序的框架(不包括状态栏),你应该使用
+ (CGFloat) window_height {
return [UIScreen mainScreen].applicationFrame.size.height;
}
+ (CGFloat) window_width {
return [UIScreen mainScreen].applicationFrame.size.width;
}
现代的答案是:
如果你的应用在iPad上支持分屏视图,这个问题就变得有点复杂了。你需要窗口的大小,而不是屏幕的大小,这可能包含2个应用程序。窗口的大小也可能在运行时发生变化。
使用应用程序主窗口的大小:
UIApplication.shared.delegate?.window??.bounds.size ?? .zero
注意:上述方法在启动时可能会在窗口成为关键窗口之前得到错误的值。如果你只需要宽度,非常推荐以下方法:
UIApplication.shared.statusBarFrame.width
使用uisscreen .main.bounds的旧解决方案将返回设备的边界。如果你的应用程序运行在分屏视图模式,它会得到错误的尺寸。
当应用程序包含2个或2个以上的窗口且窗口大小较小时,最热答案中的Self.view.window可能会显示错误的大小。