Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách xử lý swipe gesture trái/phải trên iOS App

Để xử lý cử chỉ vuốt (swipe) trái/phải trong iOS, dùng UISwipeGestureRecognizer. Có 2 cách: Storyboard hoặc code.

Phương pháp 1: Storyboard

  1. Kéo Swipe Gesture Recognizer từ Object Library vào View Controller.
  2. Chọn Gesture, Attribute Inspector > Swipe > Right (hoặc Left).
  3. Ctrl-drag từ Gesture vào code > Action: @IBAction func swipeMade(_ sender: UISwipeGestureRecognizer).
  4. Lặp lại: Thêm gesture thứ 2, set Direction = Left, connect vào cùng action.

Phương pháp 2: Code (Programmatically) - Khuyến khích


override func viewDidLoad() {
    super.viewDidLoad()
    
    let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(_:)))
    leftSwipe.direction = .left
    view.addGestureRecognizer(leftSwipe)
    
    let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(_:)))
    rightSwipe.direction = .right
    view.addGestureRecognizer(rightSwipe)
    
    // Thêm Up/Down nếu cần
    // let upSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(_:)))
    // upSwipe.direction = .up
    // view.addGestureRecognizer(upSwipe)
}

@objc func handleSwipe(_ sender: UISwipeGestureRecognizer) {
    switch sender.direction {
    case .left:
        print("Vuốt trái")
        // Logic: next page, delete, dismiss...
    case .right:
        print("Vuốt phải")
        // Logic: back, previous, show menu...
    case .up:
        print("Vuốt lên")
    case .down:
        print("Vuốt xuống")
    default:
        break
    }
}

Kết quả

Vuốt trái/phải trên màn hình > In log ra console:

Cách xử lý swipe gesture trái/phải trên iOS App

Lưu ý quan trọng

  • Mỗi UISwipeGestureRecognizer chỉ nhận diện 1 hướng. Cần tạo instance riêng cho mỗi hướng.
  • Swipe gesture yêu cầu di chuyển tối thiểu một ngưỡng (threshold) – không phù hợp cho drag/pan liên tục.
  • Để drag/pan mượt: dùng UIPanGestureRecognizer (translation, velocity).
  • Tránh conflict: Nếu view con (scroll view, collection view) cũng có gesture, dùng gestureRecognizer(_:shouldRecognizeSimultaneouslyWith:) delegate hoặc require(toFail:).
  • iOS 13+: Có thể dùng UIContextMenuInteraction cho long-press menu thay vì swipe actions cũ.