gpt4 book ai didi

ios - (Swift) 将按钮移动到有异常(exception)的随机位置

转载 作者:可可西里 更新时间:2023-11-01 01:32:48 27 4
gpt4 key购买 nike

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

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!

问题是,我在 Storyboard 上有一些按钮和标签,但我不希望按钮生成在它们之上。不知道该怎么做。感谢您的帮助!

最佳答案

您可以为您拥有的所有 UIButtonUILabel socket 创建一个数组属性,将其填充到您的 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
}
}
}

关于ios - (Swift) 将按钮移动到有异常(exception)的随机位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38989142/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com