![](/img/trans.png)
[英]How can I get the edges of a UIImageView to snap to the edges of the screen (superview)?
[英]How to get the X and Y of the edges of the screen in Swift
我已经在这里写下了这段代码,但是它并没有按照我想要的方式工作,我在所有视图中只有一个随机位置,我的意思是在屏幕边缘获得随机位置。 我该怎么做?
let viewHeight = self.view!.bounds.height
let viewWidth = self.view!.bounds.width
randomYPosition = CGFloat(arc4random_uniform(UInt32(viewHeight)))
randomXPosition = CGFloat(arc4random_uniform(UInt32(viewWidth)))
使用以下属性:
对于Max:
view.frame.maxX
view.frame.maxY
至少:
view.frame.minX
view.frame.minY
如果您确实想要屏幕的边界,那么您应该看到如何在iOS中获取屏幕的宽度和高度? ,它告诉您需要查看UIScreen
对象的尺寸。 在Swift中,代码可以执行以下操作:
let screenRect = UIScreen.mainScreen().bounds
let screenWidth = screenRect.size.width
let screenHeight = screenRect.size.height
这确实可以为您提供屏幕的宽度和高度,但是如果屏幕原点不在(0,0)位置,这将很奇怪。 如果要确定,可以添加原点的坐标:
let screenWidth = screenRect.size.width + screenRect.origin.x
let screenHeight = screenRect.size.height + screenRect.origin.y
话虽如此,通常没有什么理由去看屏幕本身。 随着iOS现在支持分屏,您的应用程序可能仅使用部分屏幕。 查看应用程序的window
,甚至只是查看控制器的view
,都更有意义。 由于它们都是UIView
,所以它们都具有bounds
属性,就像其他任何视图一样。
这应该给您一个随机数,范围分别为0-ViewHeight和0-ViewWidth
CGFloat(arc4random_uniform(UInt32(0..viewHeight)))
CGFloat(arc4random_uniform(UInt32(0..viewWidth)))
现在,您需要根据4种情况构造职位
Left side
Right side
Bottom side
Top side
如果我正确地理解了您,那么您想要的是位于视图边缘的随机点。 这意味着在视图的四个侧面,x或y是固定的。 所以这是解决方案:
topRandomPoint = CGPointMake(CGFloat(arc4random_uniform(UInt32(viewWidth))),0)
rightRandomPoint = CGPointMake(viewWidth,CGFloat(arc4random_uniform(UInt32(viewHeight))))
bottomRandomPoint = CGPointMake(CGFloat(arc4random_uniform(UInt32(viewWidth))),viewHeight)
leftRandomPoint = CGPointMake(0,CGFloat(arc4random_uniform(UInt32(viewHeight))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.