2014-10-08 45 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