ios 以整数形式获取 Swift 中的屏幕大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30189136/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:57:44  来源:igfitidea点击:

Get Screen size in Swift as Integer

iosswift

提问by Zen5656

For positioning an element random in the screen but within the boundarys I need the resolution/screen size in swift. I already fount out how to get it with CGGraphics. Unfortunately I have to calculate a bit and need it as type UInt32, not CGFloat. I cannot use casting that way. Any ideas?

为了在屏幕中随机定位元素但在边界内,我需要快速的分辨率/屏幕尺寸。我已经找到了如何使用 CGGraphics 获得它。不幸的是,我必须计算一下并需要它作为类型UInt32,而不是CGFloat。我不能那样使用铸造。有任何想法吗?

let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
//What I want to do
let screenHeight = screenSize.height-arc4random_uniform(screenSize.height)

回答by Vasil Garov

If you want random X and Y positions for your element you can do something like this:

如果您想要元素的随机 X 和 Y 位置,您可以执行以下操作:

let screenSize = UIScreen.main.bounds
let randomXPos = CGFloat(arc4random_uniform(UInt32(screenSize.width)))
let randomYPos = CGFloat(arc4random_uniform(UInt32(screenSize.height)))

Swift 4.2

斯威夫特 4.2

let screenSize = UIScreen.main.bounds
let randomXPos = CGFloat.random(in: 0..<screenSize.width)
let randomYPos = CGFloat.random(in: 0..<screenSize.height)

回答by Fatti Khan

To get the value direct in Int use this code

要直接在 Int 中获取值,请使用此代码

var bounds: CGRect = UIScreen.mainScreen().bounds
    var w:Int  = Int(self.bounds.size.width)
    var h:Int  = Int(self.bounds.size.height)

All you have to do is that convert the returning value from CGFloat to Integer

您所要做的就是将返回值从 CGFloat 转换为 Integer

Use following code to Get the value of screen height width and then convert the CGFloat to Int

使用以下代码获取屏幕高度宽度的值,然后将CGFloat转换为Int

var bounds: CGRect = UIScreen.mainScreen().bounds
var width:CGFloat = bounds.size.width
var height:CGFloat = bounds.size.height

SWIFT 4.2

斯威夫特 4.2

let bounds: CGRect = UIScreen.main.bounds
let width:CGFloat = bounds.size.width
let height:CGFloat = bounds.size.height

回答by Vijay yadav

you try like this

你试试这样

let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
let screenWidth = screenSize.width * 0.75

回答by Dharmesh Kheni

I think this is what you need:

我认为这就是你需要的:

let screenHeight = screenSize.height - CGFloat(arc4random_uniform(UInt32(screenSize.height)))