问题
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?
回答1:
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()
}
回答2:
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()
}
回答3:
Your code is ok
please remove end gesture condition from your code, It will work fine
@objc func btnDeleteLongPress(gesture : UILongPressGestureRecognizer)
{
self.textDocumentProxy.deleteBackward()
}
来源:https://stackoverflow.com/questions/39247922/long-press-delete-key-of-a-custom-keyboard-in-swift