用户键入时替换字符

时间:2017-05-28 13:37:14

标签: ios swift uitextfield

尝试用字符_

替换空格
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
}

麻烦的是,在键入空格后面的字符后替换空格。

4 个答案:

答案 0 :(得分:5)

方法textField(_, shouldChangeCharactersIn:, replacementString:)是一个查询,你不应该在那里放置副作用。而是创建一个IBAction并将其附加到editingChanged UIControlEvent ...

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

答案 1 :(得分:0)

你需要在关键时刻制作逻辑,关键事件...... 要在key down事件中询问key_code ==' ENTER'(我认为它的13个代码),如果它是在输入_中写入并返回false,则打破事件并正确地完成工作...我用javascript做了类似的事情

答案 2 :(得分:0)

尝试使用此代码,您将获得主要想法

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    var text = textField.text! + string

    if (text.range(of: " ") != nil) {
        text = text.replacingOccurrences(of: " ", with: "_", options: .literal, range: nil)
        textField.text! = text
        return false
    }

    return true
}

答案 3 :(得分:0)

您可以尝试将此扩展名用于String

extension String {
    func removingWhitespaces() -> String {
        return components(separatedBy: .whitespaces).joined()
    }
}

使用:

if textField.tag == 0 {
    username = textField.text!
    username = username.replacingOccurrences(of: " ", with: "_", options: .literal, range: nil)
    username.removingWhitespaces()
    textField.text! = username
}
return true