我想使用Swift代码在我的应用中正确定位项目,无论屏幕尺寸是多少。例如,如果我想要一个按钮占屏幕宽度的75%,我可以像(screenWidth * .75)
那样做按钮的宽度。我发现这可以通过
CGFloat screenWidth = screenSize.width;
CGFloat screenHeight = screenSize.height;
不幸的是,我不确定如何将其转换为Swift。有没有人有想法?
谢谢!
答案 0 :(得分:579)
在Swift 3.0中
let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
在较旧的时候: 做这样的事情:
let screenSize: CGRect = UIScreen.mainScreen().bounds
然后您可以像这样访问宽度和高度:
let screenWidth = screenSize.width
let screenHeight = screenSize.height
如果你想要75%的屏幕宽度,你可以去:
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
}