如何解决如何快速删除字母 uitextfield text 之间的多余空格
我在 viewController 中有名为 txtCompanyName 的 uiTextfield。我想问一下如何防止用户在字母之间输入额外的空格
var companyName = txtCompanyName.text.replacingOccurrences(of: "\"",with: "",options: Nsstring.CompareOptions.literal,range:nil)
解决方法
您可以继承 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
}
}
,
如果您希望在输入时忽略空格“”,您应该使用 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
}
希望你能明白这一点,这会有所帮助。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。