如何将按钮移动到随机位置? (迅速)

时间:2014-09-27 13:29:59

标签: ios xcode swift uikit

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

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

我正在使用Xcode 6.

1 个答案:

答案 0 :(得分:4)

将此用于按钮的@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,则在布置子视图时,您的按钮可以快照回原点位置。请参阅此问题的解决方案here