Part of a project that I am working on requires me to make an object be moved using touch. I'm currently running Swift 3.1 and Xcode 8.3.3. The 7th line gives me errors saying:
Value of type
'Set<UITouch>'
has no member 'location
'
but I have looked up the documentation and it is a member. Is there some workaround? I only need to move the image based on touch and drag.
import UIKit
class ViewController: UIViewController {
var thumbstickLocation = CGPoint(x: 100, y: 100)
@IBOutlet weak var Thumbstick: UIButton!
override func touchesBegan(_ touches:Set<UITouch>, with event: UIEvent?) {
let lastTouch : UITouch! = touches.first! as UITouch
thumbstickLocation = touches.location(in: self.view)
Thumbstick.center = thumbstickLocation
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let lastTouch : UITouch! = touches.first! as UITouch
thumbstickLocation = lastTouch.location(in: self.view)
Thumbstick.center = thumbstickLocation
}
The compiler error is correct,
Set<UITouch>
has no memberlocation
.UITouch
has propertylocation
.What you actually need to write is
thumbstickLocation = lastTouch.location(in: self.view)
to move an object to where the touches began. You can also make your code more concise by writing the body of both functions in a single line.In general, you should not use force unwrapping of optionals, but with these two functions, you can be sure that the
touches
set will have exactly one element (unless you set the view'sisMultipleTouchEnabled
property totrue
, in which case it will have more than one element), sotouches.first!
will never fail.