Nico Baum Nico Baum - 1 month ago 24
Swift Question

Counting with a button click

I have an inexplicable problem in my swift code. I am creating a simple game where you have to tab a button and with every click the button change his position. I want to count these and the counting is working fine but the problem is that at the first klick the button changes the (random) position to the top left corner and doesn't change the position any more.

Here is a part of my code:

@IBAction func btnPressed(sender: AnyObject) {
refresh()
clickCount()
}

func refresh() {
let XPosition = CGFloat(arc4random_uniform(UInt32(275)) + 50)
let YPosition = CGFloat(arc4random_uniform(UInt32(517)) + 75)
btn.center = CGPointMake(XPosition, YPosition)
}

func clickCount() {
btnCount = btnCount + 1
scoreLabel.text = "\(btnCount)"
}

override func viewDidLoad() {
super.viewDidLoad()
buttonElement()
self.view.backgroundColor = UIColor.blackColor()
}

override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
refresh()
}


I am looking forward that you can help me,
thanks a lot beforehand,

Nico

Answer

I tested you code, and it will work if you do the following: Go to your Storyboard and click on "File Inspector", deselect "Use Size Classes" and "Use Auto Layout".

Comments