Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long press delete key of a custom keyboard in swift

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?

like image 924
Khadija Daruwala Avatar asked Sep 12 '25 18:09

Khadija Daruwala


1 Answers

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()
}
like image 148
aatalyk Avatar answered Sep 14 '25 09:09

aatalyk