3

I am making a custom keyboard. The delete key in the keyboard works fine for single tap. But it does not work for long press.I want to implement the long press on the delete key so that when the user holds down the delete button, the keyboard continuously deletes like in the standard ios keyboard. I referred to a couple of solutions on Stackoverflow, like- https://stackoverflow.com/a/26234876/6077720, https://stackoverflow.com/a/25633313/6077720, https://stackoverflow.com/a/30711421/6077720

But none of it worked for me. I also tried this code:

  override func viewDidLoad() {
    super.viewDidLoad()
    textDocument = self.textDocumentProxy

    var longPress = UILongPressGestureRecognizer(target: self, action: #selector(self.longPress))
    self.deleteKeyPressed.addGestureRecognizer(longPress)
}

func longPress(gesture: UILongPressGestureRecognizer) {
    if gesture.state == .Ended {
        print("Long Press")
        self.textDocumentProxy.deleteBackward()

    }
}

But after writing this code my keyboard does not appear only. Can anyone please help me?

Community
  • 1
  • 1
Khadija Daruwala
  • 1,185
  • 3
  • 25
  • 54

3 Answers3

13

Try this code below

var timer: NSTimer?

override func viewDidLoad() {
   super.viewDidLoad()
   textDocument = self.textDocumentProxy

   var longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(KeyboardViewController.longPressHandler(_:)))

   eraseButton.addGestureRecognizer(longPressRecognizer)
}

func longPressHandler(gesture: UILongPressGestureRecognizer) {
    if gesture.state == .Began {
        timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(KeyboardViewController.handleTimer(_:)), userInfo: nil, repeats: true)
    } else if gesture.state == .Ended || gesture.state == .Cancelled {
        timer?.invalidate()
        timer = nil
    }
}

func handleTimer(timer: NSTimer) {
    self.deleteText()
}
aatalyk
  • 391
  • 4
  • 15
0
 override func viewDidLoad() {
    super.viewDidLoad()
    let longPress = UILongPressGestureRecognizer(target: self, action: #selector(KBViewController.handleLongPress(_:)))
    longPress.minimumPressDuration = 0.5
    longPress.numberOfTouchesRequired = 1
    longPress.allowableMovement = 0.5
    row3B11.addGestureRecognizer(longPress)

}

    func handleLongPress(_ gestureRecognizer: UIGestureRecognizer) {
    textDocumentProxy.deleteBackward()
}
Jeacovy Gayle
  • 447
  • 9
  • 9
  • Some explanation what this code does and why it solves the problem would improve the answer quite a lot. – JJJ Feb 15 '17 at 17:44
0

Your code is ok

please remove end gesture condition from your code, It will work fine

@objc func btnDeleteLongPress(gesture : UILongPressGestureRecognizer)
{
    self.textDocumentProxy.deleteBackward()
}
Anjali jariwala
  • 410
  • 5
  • 15