Để 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
- Kéo Swipe Gesture Recognizer từ Object Library vào View Controller.
- Chọn Gesture, Attribute Inspector > Swipe > Right (hoặc Left).
- Ctrl-drag từ Gesture vào code > Action:
@IBAction func swipeMade(_ sender: UISwipeGestureRecognizer). - 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:

Lưu ý quan trọng
- Mỗi
UISwipeGestureRecognizerchỉ 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ặcrequire(toFail:). - iOS 13+: Có thể dùng
UIContextMenuInteractioncho long-press menu thay vì swipe actions cũ.