Swift:确定 iOS 屏幕大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24110762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift: Determine iOS Screen size
提问by Z-Tech
I would like to use Swift code to properly position items in my app for no matter what the screen size is. For example, if I want a button to be 75% of the screen wide, I could do something like (screenWidth * .75)
to be the width of the button. I have found that this could be determined in Objective-C by doing
无论屏幕大小如何,我都想使用 Swift 代码在我的应用程序中正确定位项目。例如,如果我想要一个按钮(screenWidth * .75)
的宽度为屏幕的 75%,我可以做一些类似于按钮宽度的操作。我发现这可以在 Objective-C 中通过这样做来确定
CGFloat screenWidth = screenSize.width;
CGFloat screenHeight = screenSize.height;
Unfortunately, I am unsure of how to convert this to Swift. Does anyone have an idea?
不幸的是,我不确定如何将其转换为 Swift。有没有人有想法?
Thanks!
谢谢!
回答by Goppinath
In Swift 3.0
在 Swift 3.0 中
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
In older swift: Do something like this:
在较旧的 swift 中:做这样的事情:
let screenSize: CGRect = UIScreen.mainScreen().bounds
then you can access the width and height like this:
然后你可以像这样访问宽度和高度:
let screenWidth = screenSize.width
let screenHeight = screenSize.height
if you want 75% of your screen's width you can go:
如果你想要屏幕宽度的 75%,你可以去:
let screenWidth = screenSize.width * 0.75
Swift 4.0
斯威夫特 4.0
// Screen width.
public var screenWidth: CGFloat {
return UIScreen.main.bounds.width
}
// Screen height.
public var screenHeight: CGFloat {
return UIScreen.main.bounds.height
}
In Swift 5.0
在 Swift 5.0 中
let screenSize: CGRect = UIScreen.main.bounds