3 回答
TA贡献1934条经验 获得超2个赞
如何在iOS中获取屏幕尺寸?
您发布的代码的问题在于,您要依靠视图的大小来匹配屏幕的大小,而且正如您所看到的,情况并非总是如此。如果需要屏幕尺寸,则应查看代表屏幕本身的对象,如下所示:
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
拆分视图的更新:在评论中,Dmitry问:
如何在拆分视图中获取屏幕尺寸?
上面给出的代码即使在分屏模式下也报告屏幕的大小。使用分屏模式时,应用程序的窗口会更改。如果上面的代码没有提供您所期望的信息,那么像OP一样,您正在寻找错误的对象。但是,在这种情况下,您应该查看窗口而不是屏幕,如下所示:
CGRect windowRect = self.view.window.frame;
CGFloat windowWidth = windowRect.size.width;
CGFloat windowHeight = windowRect.size.height;
斯威夫特4.2
let screenRect = UIScreen.main.bounds
let screenWidth = screenRect.size.width
let screenHeight = screenRect.size.height
// split screen
let windowRect = self.view.window?.frame
let windowWidth = windowRect?.size.width
let windowHeight = windowRect?.size.height
TA贡献1876条经验 获得超7个赞
小心[UIScreen mainScreen]也包含状态栏,如果要检索应用程序的框架(不包括状态栏),则应使用
+ (CGFloat) window_height {
return [UIScreen mainScreen].applicationFrame.size.height;
}
+ (CGFloat) window_width {
return [UIScreen mainScreen].applicationFrame.size.width;
}
TA贡献1820条经验 获得超2个赞
我已经将上述一些Objective-C答案翻译成了Swift代码。每次翻译都参考原始答案。
主要答案
let screen = UIScreen.main.bounds
let screenWidth = screen.size.width
let screenHeight = screen.size.height
简单功能答案
func windowHeight() -> CGFloat {
return UIScreen.mainScreen().applicationFrame.size.height
}
func windowWidth() -> CGFloat {
return UIScreen.mainScreen().applicationFrame.size.width
}
设备方向答案
var screenHeight : CGFloat
let statusBarOrientation = UIApplication.sharedApplication().statusBarOrientation
// it is important to do this after presentModalViewController:animated:
if (statusBarOrientation != UIInterfaceOrientation.Portrait
&& statusBarOrientation != UIInterfaceOrientation.PortraitUpsideDown){
screenHeight = UIScreen.mainScreen().applicationFrame.size.width
} else {
screenHeight = UIScreen.mainScreen().applicationFrame.size.height
}
记录答案
let screenWidth = UIScreen.mainScreen().bounds.size.width
let screenHeight = UIScreen.mainScreen().bounds.size.height
println("width: \(screenWidth)")
- 3 回答
- 0 关注
- 1828 浏览
添加回答
举报