如何防止UIViews接触

时间:2017-06-20 21:14:46

标签: ios swift

所以我在屏幕中央有一个主要的Imageview和150 x 150,我以编程方式创建具有随机x和y值以及随机宽度/高度的视图(这些是相同的值)。我希望视图围绕主视图,但不要触摸它。同样在y轴上我有一个tabbar,其中包含self.view.frame和35的高度,我也不想让这些视图接触。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

为什么不随机化极坐标(角度和半径,参考是图像视图的中心)而不是笛卡尔坐标(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)

enter image description here

答案 1 :(得分:0)

func intersects(_ rect2: CGRect) -> Bool

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