代码之家  ›  专栏  ›  技术社区  ›  Khadija Daruwala

在swift中长按自定义键盘的删除键

  •  3
  • Khadija Daruwala  · 技术社区  · 8 年前

    我正在制作一个自定义键盘。键盘上的删除键可以很好地进行单次点击。但这在长期的压力下是行不通的。我想实现长按delete键,这样当用户按住delete按钮时,键盘会像标准ios键盘一样不断删除。我提到了几个关于Stackoverflow的解决方案,比如- https://stackoverflow.com/a/26234876/6077720 , https://stackoverflow.com/a/25633313/6077720 , https://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 回复  |  直到 7 年前
        1
  •  13
  •   aatalyk    8 年前

    尝试下面的代码

    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
  •  0
  •   Jeacovy Gayle    7 年前
     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
  •  0
  •   Anjali jariwala    6 年前

    您的代码正常

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

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