2017-04-18 100 views
1

我想根據當前觸摸的次數更改UIView的顏色。我已經設法通過一個單一的觸摸創建此:獲取手指觸摸UIView的次數

class colorChangerViewClass: UIView { 

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
     setColor(color: .blue) 
     print("touchesBegan") 
    } 

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { 
     setColor(color: .green) 
     print("touchesEnded") 
    } 


    func setColor(color: UIColor) { 
    self.backgroundColor = color 
    } 
} 

但我很努力實施多點觸摸。我覺得我在這裏不理解某些東西。

UIView是否有一個屬性來檢查有多少手指正在接觸它?

我可以檢查每次發生新的touchesBegan或touchesEnded。

回答

4

首先在你的子類實現多點觸摸

self.isMultipleTouchEnabled = true 

內。然後你的觸摸事件的功能,你可以得到所有接觸與您的UIView類的事件。

let touchCount = event?.touches(for: self)?.count 
+0

'事件.touches(爲:個體經營)?'返回一個UITouch集,而不是觸摸的UIView的 – Marmelador

+0

我又忘了加計數檢查,請 – abdullahselek

+0

我量現在遇到了一個新問題:當從UIView中提起2個手指時,它會將其視爲一個事件。因此觸發'touchesEnded',但在查詢'event?.touches(for:self)?count'時返回'2'。 因此,使其與'UIView'上的2個手指無法區分並解除其中一個。 – Marmelador

1

確保UIViewisMultipleTouchEnabled = true,默認爲false

然後改變touchesBegan方法

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
     setColor(color: .blue) 
     let touchCount = event?.touches(for: self)?.count 
    }