亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在iOS中獲取屏幕的寬度和高度?

如何在iOS中獲取屏幕的寬度和高度?

iOS
忽然笑 2019-11-21 11:11:02
如何在iOS中獲取屏幕尺寸?目前,我使用:lCurrentWidth = self.view.frame.size.width;lCurrentHeight = self.view.frame.size.height;在viewWillAppear:和willAnimateRotationToInterfaceOrientation:duration:第一次獲得整個屏幕尺寸。第二次我得到的屏幕減去導航欄。
查看完整描述

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


查看完整回答
反對 回復 2019-11-21
?
幕布斯6054654

TA貢獻1876條經驗 獲得超7個贊

小心[UIScreen mainScreen]也包含狀態欄,如果要檢索應用程序的框架(不包括狀態欄),則應使用


+ (CGFloat) window_height   {

    return [UIScreen mainScreen].applicationFrame.size.height;

}


+ (CGFloat) window_width   {

    return [UIScreen mainScreen].applicationFrame.size.width;

}


查看完整回答
反對 回復 2019-11-21
?
DIEA

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)")


查看完整回答
反對 回復 2019-11-21
  • 3 回答
  • 0 關注
  • 1919 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號