Leem.fin Leem.fin - 27 days ago 15
Swift Question

local variable update itself , why

I created a

UIView
component (in main storyboard it occupies the whole screen). The class it linked to is called
MyFullView
which looks like this:

import UIKit

class MyFullView: UIView {
var myTouch: UITouch?

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
// I only initialized myTouch here.
myTouch = UITouch()
myTouch = touches.first
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
// I just print out myTouch location, magically the value is updated for each finger movement, why?
print("myTouch = \(myTouch?.location(in: self))")
super.touchesMoved(touches, with: event)
}
}


I declared the variable
myTouch
& initialized it in
touchesBegan
callback. I don't have any code update the value of
myTouch
.

But when I run my app in emulator, mouse click & move/drag, I can see the log .e.g.:

myTouch = Optional((100.5, 117.0))
myTouch = Optional((99.5, 117.0))
myTouch = Optional((99.0, 117.0))
myTouch = Optional((98.5, 117.0))
myTouch = Optional((98.5, 118.0))
myTouch = Optional((98.0, 118.0))
myTouch = Optional((97.5, 118.0))
...


Why & How the hell does
myTouch
variable update the value of itself? I don't understand, could someone please explain to me what is the magic?

Answer

Your answer lies in the second line here:

        myTouch = UITouch()
        myTouch = touches.first

You have assigned myTouch to the first object in touches. When you get touch events, it happens that the UITouch will be the same instance for the lifecycle of the touch (until you get a finished or cancelled).

So you're seeing the positional updates of the touch in touchesMoved.

If you want to have the original location, you will need to store it then.

Note your code will have issues with multi touch.

Comments