2017-09-01 24 views
2

Une partie d'un projet sur lequel je travaille nécessite de faire bouger un objet en utilisant le toucher. Je cours actuellement Swift 3.1 et Xcode 8.3.3. La 7ème ligne me donne des erreurs disant:Set <UITouch> n'a pas de membre "location"

Valeur de type 'Set<UITouch>' n'a pas membre « location »

mais je l'ai regardé la documentation et il est membre. Y at-il une solution de contournement? J'ai seulement besoin de déplacer l'image basée sur le toucher et le glisser.

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 
} 

Répondre

0

L'erreur du compilateur est correct, Set<UITouch> n'a pas membre location. UITouch a la propriété location.

Ce que vous avez réellement besoin d'écrire est thumbstickLocation = lastTouch.location(in: self.view) pour déplacer un objet à l'endroit où les contacts ont commencé. Vous pouvez également rendre votre code plus concis en écrivant le corps des deux fonctions sur une seule ligne.

En général, vous ne devriez pas utiliser la force déballant de optionals, mais avec ces deux fonctions, vous pouvez être sûr que le touches ensemble aura un seul élément (sauf si vous définissez isMultipleTouchEnabled propriété à true, du point de vue auquel cas il aura plus d'un élément), donc touches.first! n'échouera jamais.

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) 
    } 
} 
1

location est en effet pas un membre de Set<UITouch>. Vous devez accéder à un élément UITouch de l'ensemble pour y accéder.

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

... mais il est préférable d'y accéder en toute sécurité en utilisant if let ou guard let:

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