(Swift)将按钮移动到随机位置,但有例外情况

3
我正在尝试将一个标签移动到一个随机位置,我已经用下面的代码做到了这一点。
let buttonWidth = self.samea.frame.width
        let buttonHeight = self.samea.frame.height

        // Find the width and height of the enclosing view
        let viewWidth = self.samea.superview!.bounds.width
        let viewHeight = self.samea.superview!.bounds.height

        // Compute width and height of the area to contain the button's center
        let xwidth = viewWidth - buttonWidth
        let yheight = viewHeight - buttonHeight

        // Generate a random x and y offset
        let xoffset = CGFloat(arc4random_uniform(UInt32(xwidth)))
        let yoffset = CGFloat(arc4random_uniform(UInt32(yheight)))

        // Offset the button's center by the random offsets.
        self.newButtonX = xoffset + buttonWidth/2
        self.newButtonY = yoffset + buttonHeight/2
        self.samea.center.x = self.newButtonX!
        self.samea.center.y = self.newButtonY!

问题是,我在故事板上有一些按钮和标签,我不希望按钮生成在它们的顶部。不确定如何做到这一点。 感谢任何帮助!


你能否添加图片来说明具体发生了什么。 - Viraj Padsala
@VirajPadsala 我在屏幕底部附近有两个粉色按钮。我的另一个按钮会随机出现在屏幕的任何位置。当它出现时,我希望它避免与这两个粉色按钮接触。 - Ash
1个回答

2

您可以创建一个数组属性,其中包含所有UIButtonUILabel的输出口,然后在viewDidLoad(_:)方法中填充它。然后,当您生成随机值时,可以将它们放入while循环中并循环遍历这些值。

类似于以下内容。

let buttonsAndLabels = [UIView]()
var xoffset: CGFloat
var yoffset: CGFloat
var isOccupied = true
while isOccupied {
  xoffset = CGFloat(arc4random_uniform(UInt32(xwidth)))
  yoffset = CGFloat(arc4random_uniform(UInt32(yheight)))
  let frame = CGRect(x: xoffset, y: yoffset, width: buttonWidth, height: buttonHeight)

  isOccupied = false
  for view in buttonsAndLabels {
    if view.frame.intersects(frame) {
      isOccupied = true
    }
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接