Swift: Long Press Gesture Recognizer - Detect taps and Long Press

前端 未结 3 1280
情话喂你
情话喂你 2020-12-05 00:11

I want to wire an action such that if the gesture is a tap, it does animates an object in a particular way but if the press duration was more than .5 secs it does something

3条回答
  •  时光取名叫无心
    2020-12-05 00:57

    Through code without interface builder

    // Global variables declaration
    var longPressed = false
    var selectedRow = 0
    
    
    
    override func viewDidLoad() {
            super.viewDidLoad()  
            let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(ContactListTableViewController.handleLongPress(_:)))
            longPressGesture.minimumPressDuration = 1.0 // 1 second press
            longPressGesture.allowableMovement = 15 // 15 points
            longPressGesture.delegate = self
            self.tableView.addGestureRecognizer(longPressGesture)
        }
    
    // Long tap work goes here !!
    if (longPressed == true) {
    
           if(tableView.cellForRowAtIndexPath(indexPath)?.accessoryType == .Checkmark){
                    tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = .None
                    self.selectedRow -= 1
    
                    if(self.selectedRow == 0){
                        self.longPressed = false
                    }
    
                } else {
                    self.selectedRow += 1
                    tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = .Checkmark
                }
    
            } else if(self.selectedRow == 0) {
              // Single tape work goes here !!
            }
    

    But the only problem is the long press gesture runs two times. If you have found any solution do comment below !

提交回复
热议问题