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

标签 ios xcode swift uikit

我正在为 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/

相关文章:

xcode - 我正在使用 Xcode 快速编写一个基本的命令行(UDP)服务器/监听器。 #GCDAsyncUdpSocket 不会调用我的任何代表

ios - Xcode 10 错误 : Multiple commands produce after generating NSManagedObject subclass

ios - 如何使用 UIPanGestureRecognizer 旋转图像

ios - UIViewController 没有正确加载它的 xib

没有关联 Controller 的 iOS 选项卡栏项目

ios - 全局变量与直接连接在 View Controller ios 之间传递数据

ios - 将倒数计时器值重置为数组中保存的默认值

ios - dialogDidComplete : FBDialogDelegate method gets called in iOS SDK even if user cancels

ios - 为什么我无法从 swift5 中的模拟器获取设备 token ?

ios - *** 由于未捕获的异常 'NSRangeException' 而终止应用程序,原因 : '*** -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray'