萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> iOS 開發

iOS 觸控事件處理完整解析:從 UITouch 到響應者鏈

觸控事件核心物件模型

UITouch:單點觸控資訊封裝

  • window、view:觸控發生時所在視窗/視圖(可能隨手指移動變化)。
  • tapCount:短時間內連續輕觸次數(判斷單擊/雙擊)。
  • timestamp:事件產生時間(秒)。
  • phase:.began、.moved、.stationary、.ended、.cancelled。
  • location(in:)、previousLocation(in:):在指定視圖座標系中的位置。

UIEvent:事件容器

包含一組 UITouch,代表同一事件週期內所有觸控點。
allTouches 取得全部觸控;touches(for: view) 篩選特定視圖。

響應者鏈與事件分發

關鍵角色

  • UIResponder:定義事件處理介面,UIApplication、UIView、UIViewController 皆繼承。
  • First Responder:目前正在接收觸控的視圖/控制器,鏈的起點。
  • Responder Chain:視圖 → 視圖控制器 → 父視圖 → … → UIWindow → UIApplication。未處理則丟棄。

事件分發流程

  1. 硬體偵測觸控 → 封裝 UIEvent + UITouch 集合。
  2. UIApplication 分發給主 UIWindow。
  3. hitTest(_:with:) 遞迴找到最前層、可互動、包含觸控點的視圖 → First Responder。
  4. 呼叫 First Responder 四大觸控方法;若未處理,沿響應者鏈向上傳遞。

四大觸控處理方法(於 UIView/UIViewController 覆寫)


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... 更健壯、可複用。

理解觸控事件底層機制,有助於自訂複雜互動與排查手勢衝突。

copyright © 萬盛學電腦網 all rights reserved