如何删除字母 uitextfield 文本 swift 之间多余的 space

how to remove the extra space between letters uitextfield text swift

我在 viewController 中有一个名为 txtCompanyName 的 uiTextfield。我想问一下如何防止用户在字母

之间输入额外的space
var companyName = txtCompanyName.text.replacingOccurrences(of: "\"", with: "", options: NSString.CompareOptions.literal, range:nil)

如果您希望在输入时忽略空格“”,您应该使用 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
  }

希望你明白了,这对你有帮助。

您可以子类化 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
    }
}