簡體   English   中英

在Swift中,如何在觸發touchesMoved之后檢查用戶是否不再觸摸屏幕?

[英]In Swift, how can I check that a user is no longer touching the screen after touchesMoved is triggered?

我需要知道用戶開始觸摸屏幕,然后知道何時不再觸摸屏幕。

通過touchesBegantouchesEnded我可以獲得此類信息。 但是,如果用戶在滑動手指,那么我知道他是從touchesMoved開始的。
但是,我無法檢查他何時不再觸摸屏幕。 基本上,在用戶停止滑動后, touchesEnded不會觸發。 有任何想法嗎?

我的代碼示例:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {


    if let touch = touches.first {
    print("Finger touched!")
    }
    super.touchesBegan(touches, withEvent:event)
}


override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {

        print("Finger is swipping!")

    }
    super.touchesBegan(touches, withEvent:event)
}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {

        print("finger is not touching.") //this will not fire if finger stopped swipping

    }
    super.touchesBegan(touches, withEvent:event)
}

你說:

print("finger is not touching.") //this will not fire if finger stopped swipping

沒錯,如果手指停止移動它不會觸發。 但是,如果手指離開屏幕(停止觸摸)火,這是你問有關(“不再觸摸屏”)。

在Swift 3中工作

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if touches.first != nil {
        print("Finger touched!")
    }

}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if touches.first != nil {
        print("finger is not touching.")  
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if touches.first != nil {
        print("Touch Move")
    }
}

touchesBegan:withEvent:觸摸同一屏幕事件的一部分時,總是需要一個或多個手指被觸摸。 touchesMoved:withEvent:事件中的一根或多根手指移動時會觸發。 touchesEnded:withEvent:當觸摸事件中的一根或多根手指從屏幕上移開時會被觸發。 最后,如果整個事件都無效(即取消),則調用touchesCancelled:withEvent:

對於給定的事件,您將始終會收到一個或多個touchesBegan:withEvent:調用,可能會多次調用touchesMoved:withEvent ,然后會多次調用touchesEnded:withEvent:touchesCancelled:withEvent:

這里要考慮的幾件事:

  1. 即使不執行任何操作,也應始終實現所有這四個方法,以防止部分事件沿響應者鏈上升(這是超級實現的作用)。
  2. 如果您正在處理事件,則不應調用super。
  3. 如果因為要在響應者鏈上調度事件而調用super,則必須調用正確的super方法(您在touchesMoved:withEvent實現中的super上調用touchesBegan:withEvent:

要具體回答您的問題,您可以實現touchesEnded:withEvent來了解用戶何時停止通過事件中的一次或多次觸摸來停止觸摸屏幕。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM