簡體   English   中英

如何將按鈕移動到隨機位置? (迅速)

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

我正在為iPhone創建一個非常簡單的應用程序。

只是不知道如何在Swift中將按鈕(圖像)移動到隨機位置(但在屏幕上)。

我正在使用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
}

警告 :如果啟用了“自動布局”,則在布局子視圖時,您的按鈕可能會恢復到其原始位置。 這里查看此問題的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM