如何将按钮移动到随机位置?(迅速) [英] How to move button to random position? (Swift)

查看:48
本文介绍了如何将按钮移动到随机位置?(迅速)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm creating a very simple app for iPhone.

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

Just don't know how to make the button (image) move to random position (but on the screen) when it's touched, in Swift.

我使用的是 Xcode 6.

I'm using 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,当子视图布局时,您的按钮可能会弹回其原始位置.在此处查看此问题的解决方案.

Warning: If you have AutoLayout enabled, your button could snap back to its original location when the subviews are laid out. See the solution to this problem here.

这篇关于如何将按钮移动到随机位置?(迅速)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆