Set<UITouch> has no member "location"

517 views Asked by At

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
}
2

There are 2 answers

0
Dávid Pásztor On BEST ANSWER

The compiler error is correct, Set<UITouch> has no member location. UITouch has property location.

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's isMultipleTouchEnabled property to true, in which case it will have more than one element), so touches.first! will never fail.

class ViewController: UIViewController {

    var thumbstickLocation = CGPoint(x: 100, y: 100)

    @IBOutlet weak var Thumbstick: UIButton!

    override func touchesBegan(_ touches:Set<UITouch>, with event: UIEvent?) {
        Thumbstick.center = touches.first!.location(in: self.view) 
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        Thumbstick.center = touches.first!.location(in: self.view)
    }
}
0
Tamás Sengel On

location is indeed not a member of Set<UITouch>. You should access a UITouch element of the set to access it.

thumbstickLocation = touches.first!.location(in: self.view)

...but it's better to access it safely by using if let or guard let:

if let lastTouch = touches.first {
    thumbstickLocation = lastTouch.location(in: self.view)
    Thumbstick.center = thumbstickLocation
}