2016-01-20 62 views
1

我正在尋找一種方法來檢測用戶是否在屏幕上(屏幕持續1秒)我嘗試使用計時器,但我沒有工作。這是我現在的代碼。Swift 2.0如何檢測用戶是否持有,而不是僅僅點擊

var brakeTimer = NSTimer() 

func update() { 
    print("The user is holding the screen") 
} 

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
    var brakeTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true) 
} 


override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { 
    brakeTimer.invalidate() 
} 
+2

我認爲你正在尋找一個[UILongPressGestureRecognizer(https://developer.apple.com/library/ios/documentation/UIKit/Reference/UILongPressGestureRecognizer_Class/) – Cristik

回答

6

在界面上的「保持」在iOS開發中通常被稱爲「長按」。以下是如何設置這些之一:

let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "longPressed:") 
     self.view.addGestureRecognizer(longPressRecognizer) 

func longPressed(sender: UILongPressGestureRecognizer) 
    { 
     println("longpressed") 
    } 

與之相對簡單的水龍頭識別器,當用戶在屏幕上簡單的水龍頭,而不是持有一段較長的時間,這將觸發。

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "tapped:") 
     self.view.addGestureRecognizer(tapGestureRecognizer) 

    func tapped(sender: UITapGestureRecognizer) 
    { 
     println("tapped") 
    } 
+1

您也可以使用之間的計時器按下一個手指然後釋放,但使用LongPress按照這裏建議的方式更適合大多數用途。 – Jeremiah

+0

@Jeremiah是啊我想時間UITouchDown和UITouchUpInside之間的區別,類似的東西? – Woodstock

相關問題