我想使用Swift代码在我的应用程序中正确定位项目,无论屏幕大小是什么。例如,如果我想要一个按钮的宽度是屏幕宽度的75%,我可以这样做(screenWidth * .75)作为按钮的宽度。我发现这可以在Objective-C中通过做

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

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

谢谢!


当前回答

在Swift 5.0中

let screenSize: CGRect = UIScreen.main.bounds

斯威夫特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 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 5.0中

let screenSize: CGRect = UIScreen.main.bounds

斯威夫特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 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