用户输入时替换字符

luk*_*uke 1 uitextfield ios swift

尝试用字符_替换空格

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField.tag == 0 {
        username = textField.text!
        username = username.replacingOccurrences(of: " ", with: "_", options: .literal, range: nil)
        textField.text! = username
    }
    return true
}
Run Code Online (Sandbox Code Playgroud)

麻烦的是,键入空格后的字符后,空格被替换了。

Dan*_* T. 5

该方法textField(_, shouldChangeCharactersIn:, replacementString:)是一个查询,您不应在其中添加副作用。而是制作一个IBAction并将其附加到editingChangedUIControlEvent ...

@IBAction func editingChanged(_ sender: UITextField) {
    sender.text = sender.text?.replacingOccurrences(of: " ", with: "_")
}
Run Code Online (Sandbox Code Playgroud)