【问题标题】:how to remove the extra space between letters uitextfield text swift如何快速删除字母uitextfield文本之间的多余空格
【发布时间】:2020-12-23 19:19:17
【问题描述】:

我在 viewController 中有一个名为 txtCompanyName 的 uiTextfield。我想问一下如何防止用户在字母之间输入额外的空格

var companyName = txtCompanyName.text.replacingOccurrences(of: "\"", with: "", options: NSString.CompareOptions.literal, range:nil)

【问题讨论】:

    标签: swift uikit uitextfield


    【解决方案1】:

    您可以继承 UITextField 并避免前导空格以及双尾随空格和单词之间的双空格,如下所示:

    class SingleSpaceField: UITextField {
        override func willMove(toSuperview newSuperview: UIView?) {
            // adds a target to the textfield to monitor when the text changes
            addTarget(self, action: #selector(editingChanged), for: .editingChanged)
            // sets the keyboard type to alphabet
            keyboardType = .alphabet
            // set the text alignment to left
            textAlignment = .left
            // sends an editingChanged action to force the textfield to be updated on launch
            sendActions(for: .editingChanged)
        }
        @objc func editingChanged() {
            // this saves the caret position
            let selectedRange = selectedTextRange
            // this avoids leading spaces
            text = text!.replacingOccurrences(of: #"^\s"#, with: "", options: .regularExpression)
            // this avois double spaces anywhere in your field
            text = text!.replacingOccurrences(of: #"\s{2,}"#, with: " ", options: .regularExpression)
            // this restores the caret position
            selectedTextRange = selectedRange
        }
    }
    

    【讨论】:

      【解决方案2】:

      如果您希望在输入时忽略空格“”,则应使用 UITextFieldDelegate 方法之一:

        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
          guard let text = textField.text else {
            return false
          }
          if text == " " {
            return false
          }
          return true
        }
      

      希望你能明白这一点,这会有所帮助。

      【讨论】:

      • guard let text = textField.text else 永远不会失败。 UITextField 默认值为空字符串
      • @LeoDabus 我们不能总是确定..)) 但是,这实际上主要是为了消除可选性。另一方面,我们可以使用类似的东西 - let currentText = textField.text ?? ""
      • 即使您将 nil 分配给它并在下一行获取它的值,它也会返回一个空字符串。您可以简单地强制解包结果text!
      猜你喜欢
      • 1970-01-01
      • 2022-07-24
      • 2015-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      相关资源
      最近更新 更多