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 關注
- 1919 瀏覽
添加回答
舉報