gpt4 book ai didi

ios - 如何将按钮移动到随机位置? ( swift )

转载 作者:行者123 更新时间:2023-11-28 10:25:48 24 4
gpt4 key购买 nike

我正在为 iPhone 创建一个非常简单的应用程序。

只是不知道如何在 Swift 中使按钮(图像)在被触摸时移动到随机位置(但在屏幕上)。

我正在使用 Xcode 6。

最佳答案

将此用于按钮的 @IBAction:

@IBAction func moveButton(button: UIButton) {
// Find the button's width and height
let buttonWidth = button.frame.width
let buttonHeight = button.frame.height

// Find the width and height of the enclosing view
let viewWidth = button.superview!.bounds.width
let viewHeight = button.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.
button.center.x = xoffset + buttonWidth / 2
button.center.y = yoffset + buttonHeight / 2
}

警告:如果启用了 AutoLayout,则在布置 subview 时,您的按钮可能会弹回其原始位置。看这个问题的解决方法here .

关于ios - 如何将按钮移动到随机位置? ( swift ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26075158/

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