【问题标题】:How to implement a fully functional backspace key in custom keyboard button swift如何在自定义键盘按钮 swift 中实现功能齐全的退格键
【发布时间】:2017-03-20 17:37:31
【问题描述】:

如何在 iOS 中为自定义键盘实现自定义退格/删除按钮,以快速响应 UITextField 委托?

【问题讨论】:

标签: swift uitextfield uikeyboard


【解决方案1】:

我为此苦苦挣扎了一段时间,所以我想我会回答这个问题。以下代码响应在作为 UITextfield 的第一响应者的 uikeyboard 上按下的自定义退格键:

// the tag for the backspace button
if tag == "<"{
        //the range of the selected text (handles multiple highlighted characters of a uitextfield)
        let range = textField.selectedTextRange?;

        // if the range is empty indicating the cursor position is 
        // singular (no multiple characters are highlighted) then delete the character 
        // in the position before the cursor
        if range!.empty {

            let start = textField.positionFromPosition(range!.start, offset: -1);
            let end = axiomBuilderTV.positionFromPosition(range!.end, offset: 0);
            axiomBuilderTV.replaceRange(axiomBuilderTV.textRangeFromPosition(start, toPosition: end), withText: "");
        }
        // multiple characters have been highlighted so remove them all
        else {
            textField.replaceRange(range!, withText: "");
        }

    }

【讨论】:

    【解决方案2】:

    您可能会发现全局方法“droplast()”很有帮助。(还有一个“dropfirst”)

    var stringToBeBackspace = "abcde"
    dropLast(stringToBeBackspace)    //.swift
    

    字符串实际上是字符的集合,所以你也可以在字符串中做滑动字符,你可能会发现“countElements”对你有很大帮助。

    【讨论】:

      【解决方案3】:

      我现在这个问题早就得到了回答,但我想分享我基于 UIKeyInput 的方法(在 iOS9 和 Xcode 7- Swift 2 上测试)。

          @IBAction func backspacePressed(btn: UIButton) {
              if btn.tag == 101 {
      
                  (textDocumentProxy as UIKeyInput).deleteBackward()
              }
          }
      

      【讨论】:

      • 什么是 textDocumentProxy ?
      【解决方案4】:

      斯威夫特 3.0.1

      此答案对退格/删除按钮作出反应,但具有限制可输入文本字段的最大字符数的额外功能。因此,如果 textField 包含的字符多于最大数量,因为以编程方式将字符串插入到 textField 中,则您无法添加字符,但可以删除它们,因为 'range.length' 仅使用删除键返回 1。

      感谢 OOPer 提供限制字符数的原始代码。 https://forums.developer.apple.com/thread/14627

      func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // Updates everytime character ie typed or deleted until Max set in textFieldLimit
          let textFieldLimit = 30
          if (range.length == 1) { // Delete button = 1 all others = 0
              return true
          } else {
              return (textField.text?.utf16.count ?? 0) + string.utf16.count - range.length <= textFieldLimit
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-17
        • 1970-01-01
        • 2020-02-16
        相关资源
        最近更新 更多