长按快速删除自定义键盘的键

时间:2016-08-31 11:05:26

标签: ios swift custom-keyboard

我正在制作自定义键盘。键盘中的删除键适用于单击。但它不适用于长按。我想在删除键上实现长按,这样当用户按下删除按钮时,键盘会像标准ios键盘一样连续删除。我在Stackoverflow上提到了几个解决方案,比如 - https://stackoverflow.com/a/26234876/6077720https://stackoverflow.com/a/25633313/6077720https://stackoverflow.com/a/30711421/6077720

但这些都不适合我。我也试过这段代码:

  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()

    }
}

但在编写此代码后,我的键盘不会出现。有人可以帮帮我吗?

3 个答案:

答案 0 :(得分:5)

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()
}

答案 1 :(得分: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()
}

答案 2 :(得分:0)

您的代码还可以

请从代码中删除结束手势条件,它将正常工作

@objc func btnDeleteLongPress(gesture : UILongPressGestureRecognizer)
{
    self.textDocumentProxy.deleteBackward()
}