(Swift)移动按钮到随机位置与例外



我正试图将标签移动到一个随机位置,我已经能够使用此代码这样做。

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!

问题是,我在故事板上有一些按钮和标签,我不希望按钮在这些顶部生成。不知道该怎么做。

您可以创建所有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
    }
  }
}

最新更新