window、view:觸控發生時所在視窗/視圖(可能隨手指移動變化)。tapCount:短時間內連續輕觸次數(判斷單擊/雙擊)。timestamp:事件產生時間(秒)。phase:.began、.moved、.stationary、.ended、.cancelled。location(in:)、previousLocation(in:):在指定視圖座標系中的位置。包含一組 UITouch,代表同一事件週期內所有觸控點。allTouches 取得全部觸控;touches(for: view) 篩選特定視圖。
UIApplication、UIView、UIViewController 皆繼承。UIEvent + UITouch 集合。UIApplication 分發給主 UIWindow。hitTest(_:with:) 遞迴找到最前層、可互動、包含觸控點的視圖 → First Responder。
override func touchesBegan(_ touches: Set, with event: UIEvent?) { }
override func touchesMoved(_ touches: Set, with event: UIEvent?) { }
override func touchesEnded(_ touches: Set, with event: UIEvent?) { }
override func touchesCancelled(_ touches: Set, with event: UIEvent?) { }
參數 touches 為當前階段相關觸控集合,event 為完整事件。
// 雙擊偵測(放在 ended 確保手指已離開)
override func touchesEnded(_ touches: Set, with event: UIEvent?) {
guard let touch = touches.first else { return }
if touch.tapCount == 2 {
view.backgroundColor = .red
} else if touch.tapCount == 1 {
// 延遲 0.3 秒執行單擊動作,若期間收到第二下則取消
perform(#selector(singleTapAction), with: nil, afterDelay: 0.3)
}
}
@objc func singleTapAction() {
view.backgroundColor = .blue
}
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
// 若在延遲期間再次觸摸,取消單擊延遲
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(singleTapAction), object: nil)
}
// 可拖曳視圖
var initialCenter = CGPoint.zero
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
guard let touch = touches.first else { return }
initialCenter = view.center
// 記錄觸控點在父視圖座標
startLocation = touch.location(in: view.superview)
}
override func touchesMoved(_ touches: Set, with event: UIEvent?) {
guard let touch = touches.first else { return }
let current = touch.location(in: view.superview)
let dx = current.x - startLocation.x
let dy = current.y - startLocation.y
view.center = CGPoint(x: initialCenter.x + dx, y: initialCenter.y + dy)
}
view.isMultipleTouchEnabled = true(預設 false)。
view.isUserInteractionEnabled = false:單一視圖忽略觸控。UIApplication.shared.beginIgnoringInteractionEvents():全域暫停事件分發(載入遮罩常用)。UIApplication.shared.endIgnoringInteractionEvents():恢復。實務上建議使用 UIGestureRecognizer 子類(UITapGestureRecognizer、UIPanGestureRecognizer 等),封裝觸控邏輯、自動處理狀態機、支援代理協作,比手寫 touches... 更健壯、可複用。
理解觸控事件底層機制,有助於自訂複雜互動與排查手勢衝突。