问题描述
无论屏幕大小如何,我都想使用Swift代码在我的应用程序中正确定位项目.例如,如果我希望按钮的宽度为屏幕宽度的75%,则可以执行(screenWidth * .75)
这样的按钮宽度.我发现这可以通过在Objective-C中确定来完成
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
CGFloat screenWidth = screenSize.width;
CGFloat screenHeight = screenSize.height;
不幸的是,我不确定如何将其转换为Swift.有人有主意吗?
Unfortunately, I am unsure of how to convert this to Swift. Does anyone have an idea?
谢谢!
推荐答案
在Swift 3.0中
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
以较早的速度:做这样的事情:
In older swift:Do something like this:
let screenSize: CGRect = UIScreen.mainScreen().bounds
然后您可以像这样访问宽度和高度:
then you can access the width and height like this:
let screenWidth = screenSize.width
let screenHeight = screenSize.height
如果您想要屏幕宽度的75%,则可以:
if you want 75% of your screen's width you can go:
let screenWidth = screenSize.width * 0.75
Swift 4.0
// Screen width.
public var screenWidth: CGFloat {
return UIScreen.main.bounds.width
}
// Screen height.
public var screenHeight: CGFloat {
return UIScreen.main.bounds.height
}
在Swift 5.0中
let screenSize: CGRect = UIScreen.main.bounds
这篇关于Swift:确定iOS屏幕大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!