小编典典

Swift:确定iOS屏幕尺寸

swift

无论屏幕大小如何,我都想使用Swift代码在我的应用程序中正确定位项目。例如,如果我希望按钮(screenWidth *.75)的宽度为屏幕宽度的75%,则可以做为按钮的宽度。我发现可以通过在Objective-C中确定

CGFloat screenWidth = screenSize.width;
CGFloat screenHeight = screenSize.height;

不幸的是,我不确定如何将其转换为Swift。有人有主意吗?

谢谢!


阅读 580

收藏
2020-07-07

共1个答案

小编典典

在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

迅捷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
2020-07-07