2017-09-01 40 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 
}