2014-09-27 136 views

回答

4

使用此爲您的按鈕的@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 
} 

警告:如果您有自動版式啓用,您可以按鍵彈回原來的位置當子視圖被佈置時。請參閱此問題的解決方案here

+0

這樣做。謝謝。 – perte 2014-09-27 14:36:47

相關問題