【问题标题】:How to move button to random position? (Swift)如何将按钮移动到随机位置? (迅速)
【发布时间】:2014-11-22 09:15:14
【问题描述】:

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

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

我正在使用 Xcode 6。

【问题讨论】:

    标签: ios xcode swift uikit


    【解决方案1】:

    将此用于按钮的@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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-22
      • 2017-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多