I'm trying to make a draggable image (monkey) takes the place of another draggable image (banana) when I'm pushing a button.
So far, I've been able to get the coordinates of the banana, and store them as the new x,y coordinates of the monkey. But, the view is not updating and the monkey does not moves to it's new place.
I'm sure that I need to update the view, but can't figure it out. I've tried to add a new subview (self.view.addSubview(monkey)) but when I do that, it's the entire view that is reset and both monkey and banana are going back to their original coordinates.
Here's the code of the action button :
@IBAction func getCoordinates (sender : AnyObject) {
var bananax = banana.frame.origin.x
var bananay = banana.frame.origin.y
var monkeyx = monkey.frame.origin.x
var monkeyy = monkey.frame.origin.y
println("Banana : \(bananax) et \(bananay)")
println("Monkey's default coordinates : \(monkeyx) et \(monkeyy)")
monkeyx = bananax
monkeyy = bananay
println("Monkey's new coordinates : \(monkeyx) et \(monkeyy)")
}
Any idea on how to update only the monkey and not reseting the entire view ?
Thanks :)
These values are just thrown away when you set monkeyx
and monkeyy
below.
var monkeyx = monkey.frame.origin.x
var monkeyy = monkey.frame.origin.y
Assigning the values below just assigns the values from one local variable to another. It does not actually change the coordinates for monkey
.
monkeyx = bananax
monkeyy = bananay
You must set the new coordinates on monkey by constructing a new CGRect
and assigning monkey
's frame
:
monkey.frame = CGRect(x: bananax, y: bananay, width: monkey.frame.size.width, height: monkey.frame.size.height)
As you are just setting monkey
's origin to banana
's origin, you can remove all the var declarations and reduce this to one line by constructing monkey
's new frame with monkey
's size and banana
's origin:
monkey.frame = CGRect(origin: banana.frame.origin, size: monkey.frame.size)