xcode 如何将按钮移动到随机位置?(迅速)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26075158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to move button to random position? (Swift)
提问by perte
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。
回答by vacawama
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.
警告:如果您启用了 AutoLayout,则在布局子视图时,您的按钮可能会弹回其原始位置。请在此处查看此问题的解决方案。