基于随机数的按钮位置 - xCode 6(swift)

时间:2014-10-08 00:40:50

标签: objective-c swift ios8 xcode6

我正在尝试将按钮移动到5个不同的位置,具体取决于随机数(1-6),我还想在标签中显示它们的随机数。

我编写了以下代码,但按钮似乎没有移动到我在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 个答案:

答案 0 :(得分:0)

感谢vacawama在评论中回答这个问题,确实禁用了Autolayout解决了这个问题。

这里有更详细的答案: -

Swift NSTimer and IBOutlet Issue

答案 1 :(得分:-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
}