2017-09-01 42 views
2

我正在处理的项目的一部分需要我使用触摸移动对象。我目前正在运行Swift 3.1和Xcode 8.3.3。第7行给我的错误说:设置<UITouch>没有会员“位置”

'Set<UITouch>'类型的值没有任何成员“location

可是我已经看过了的文档,这是一个成员。有一些解决方法吗?我只需要基于触摸和拖动来移动图像。

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 
} 

回答

0

编译器错误是正确的,Set<UITouch>没有成员locationUITouch有财产location

你实际需要写的是thumbstickLocation = lastTouch.location(in: self.view)将对象移动到触摸开始的位置。您也可以通过将两个函数的主体写入一行来使代码更加简洁。

一般情况下,你不应该使用武力展开自选的,但是这两个功能,你可以肯定的是,touches集将有一个元素(除非你视图的isMultipleTouchEnabled属性设置为true,在这种情况下,将有不止一个元素),所以touches.first!永远不会失败。

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确实Set<UITouch>成员。您应该访问该组的一个UITouch元素以访问它。

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

...但它更好地利用if letguard let安全地访问它:

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