简体   繁体   English

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

[英]How to move button to random position? (Swift)

I'm creating a very simple app for iPhone. 我正在为iPhone创建一个非常简单的应用程序。

Just don't know how to make the button (image) move to random position (but on the screen) when it's touched, in Swift. 只是不知道如何在Swift中将按钮(图像)移动到随机位置(但在屏幕上)。

I'm using Xcode 6. 我正在使用Xcode 6。

Use this for the @IBAction of your button: 将其用于按钮的@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
}

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 . 这里查看此问题的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM