2014-10-08 93 views
0

我試圖讓一個按鈕移動到5個不同的位置,具體取決於隨機數(1-6),我也想在標籤中顯示它們的隨機數。基於隨機數的按鈕位置 - xCode 6(swift)

我寫了下面的代碼,但該按鈕似乎並沒有移動到我在IF語句中指定的位置: -

import UIKit 

class game: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     // Do any additional setup after loading the view. 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 

    //Decalare display label 
    @IBOutlet var d1: UILabel! 

    //One Button declaration 
    @IBOutlet var oneBTN: UIButton! 

    @IBAction func rollBTNPress(sender: AnyObject) { 

     //Generate random number 
     var r = arc4random_uniform(5) 

    //Display dice1 number in d1 Label 
     d1.text = "\(dice1)" 


     if (r == 1) { 
      oneBTN.center = CGPointMake(10, 70); 
     } else if (r == 2) { 
      oneBTN.center = CGPointMake(30, 70); 
     } else if (r == 3) { 
      oneBTN.center = CGPointMake(50, 70); 
     } else if (r == 4) { 
      oneBTN.center = CGPointMake(70, 70); 
     } else if (r == 5) { 
      oneBTN.center = CGPointMake(90, 70); 
     } else { 
      oneBTN.center = CGPointMake(0, 70); 
     } 

    } 

} 

代碼運行,沒有任何問題彙總。但是按鈕位置似乎是隨機的,實際上它忽略了IF語句中指定的座標。

更奇怪的是,如果我註釋掉d1.text = "\(dice1)",按鈕會根據隨機數開始移動到正確的位置。

我也嘗試改變CGPointMake並使用CGPoint來代替,但我得到完全相同的行爲。

+2

自動佈局是改變你的按鈕的位置。看到在這個問題的討論:http://stackoverflow.com/questions/26227093/swift-nstimer-and-iboutlet-issue/26227531#26227531 – vacawama 2014-10-08 01:20:14

+0

這是真棒,這麼簡單,但浪費了我的很多時間!謝謝! – thefan12345 2014-10-08 14:11:50

回答

-1
@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 
} 
+1

請添加解釋如何解決方案適用於OP – techspider 2016-06-02 21:18:48