Friday, February 10, 2017

How to use Long Press Gesture in TableView Using Swift Language

1 comment :
1.Add Delegate to View Controller Class

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate

 /* Long Press Gesture Declaration */

override func viewDidLoad()
    {
        super.viewDidLoad()     
   let longPressGesture:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longPress(_:)))
        longPressGesture.minimumPressDuration = 1.0 // 1 second press
        longPressGesture.delegate = self
        self.chatTableView.addGestureRecognizer(longPressGesture)


}

Usage :


//MARK: Long Press Gesture
    func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer)
    {
        let p = longPressGestureRecognizer.location(in: self.chatTableView)
        let indexPath = self.chatTableView.indexPathForRow(at: p)
        
        if indexPath == nil
        {
        }
        else if (longPressGestureRecognizer.state == UIGestureRecognizerState.began)
        {
            showMultipleSelectionBox(indexPath: indexPath! as NSIndexPath)
        }
    }
    
    func showMultipleSelectionBox(indexPath: NSIndexPath)
    {
        let ac = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        ac.addAction(UIAlertAction(title: "Reply", style: .default){ (action) in })
        ac.addAction(UIAlertAction(title: "Share Current Message", style: .default){ (action) in })
        ac.addAction(UIAlertAction(title: "Share", style: .default){ (action) in self.pasteMethod()
        })
        ac.addAction(UIAlertAction(title: "Copy", style: .default){ (action) in self.copyMethod()
        })
        ac.addAction(UIAlertAction(title: "Edit", style: .default){ (action) in })
        ac.addAction(UIAlertAction(title: "Download", style: .default){ (action) in  })
        ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        present(ac, animated: true, completion: nil)
    }
    
    //MARK: Copy Method
    func copyMethod()
    {
        UIPasteboard.general.string = "test paste string"
        debugPrint( UIPasteboard.general.string ?? "")
    }
    
    //MARK: Paste Method
    
    func pasteMethod()
    {
        if UIPasteboard.general.string != nil
        {
        }
    }

    

1 comment :