Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> iOS

วิธีตรวจจับ Long Press Gesture ใน iOS

Long-press (กดค้าง) ตรวจจับนิ้วสัมผัสหน้าจอนานพอ ตั้งค่า Minimum Duration และจำนวนนิ้ว

อ่านรายละเอียด

ตัวอย่าง: กดค้างปุ่ม 2 วินาที แสดง Alert

ขั้นตอนที่ 1: สร้างโปรเจกต์

Xcode → New Project → Single View Application → ชื่อ "LongPressGesture"

ขั้นตอนที่ 2: เพิ่มปุ่มและ Outlet

Main.storyboard: เพิ่มปุ่ม @IBOutlet ชื่อ btnLongOutlet

ขั้นตอนที่ 3: สร้าง UILongPressGestureRecognizer

var longgesture = UILongPressGestureRecognizer

ขั้นตอนที่ 4: ตั้งค่าใน viewDidLoad

longgesture = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longPress(_:)))
longgesture.minimumPressDuration = 2
btnLongOutlet.addGestureRecognizer(longgesture)

ขั้นตอนที่ 5: สร้างฟังก์ชัน longPress

@objc func longPress(_ sender: UILongPressGestureRecognizer) {
let alertController = UIAlertController(title: "Long Press",
message: "Long Press Gesture Detected", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
}

ขั้นตอนที่ 6: รันทดสอบ

กดปุ่มค้าง 2 วินาที จะแสดง Alert

วิธีตรวจจับ Long Press Gesture ใน iOS