繁体   English   中英

如何防止UIViews接触

[英]How to keep UIViews from touching

因此,我在屏幕中央有一个主Imageview,其尺寸为150 x 150,我以编程方式创建了具有随机x和y值以及随机宽度/高度(这些值相同)的视图。 我希望视图围绕主图像视图,但不要触摸它。 同样在y轴上,我有一个标签栏,它具有self.view.frame和一个高度为35的高度,我也不希望这些视图接触。 有任何想法吗?

为什么不随机选择极坐标(角度和半径,参考点为图像视图的中心)而不是笛卡尔坐标(x和y)? 如果您有角度和半径,则控制到中心的距离会更容易。 您可以根据最终的随机宽度和高度增加半径,以使其距离中心更远,以补偿和避免碰撞。

let centerImageView = UIImageView()

//..

//Bounding circle for the image view
let centerRadius = max(centerImageView.width, centerImageView.height)

func randomFloat(min: Float, max: Float) {
    return min + (max - min) * (arc4random() / RAND_MAX)
}

//Somewhere else in your loop for generating views

let angle = randomFloat(0, Float.pi * 2)
//Dimensions of the random view
let width = randomFloat(min: 10, max: 50)
let height = randomFloat(min: 10, max: 50)
//Bounding circle, you can use an ellipse, or calculate the distance perfectly for that angle too, but this is simpler
let viewRadius = randomFloat(min: width, max: height)
//The distance from the center must be greater than the sum of both bounding circles' radiuses, plus some
let radius = centerRadius + viewRadius + randomFloat(min: 50, max: 100)
//Convert to cartesian coordinates
let x = centerImageView.center.x + cos(angle) * radius
let y = centerImageView.center.y + sin(angle) * radius

let view = UIView(frame: CGRect(x: x, y: y, width: width, height: height)

在此处输入图片说明

func intersects(_ rect2: CGRect) -> Bool

如果中心视图与新创建的视图相交,则随机生成新框架。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM