在Swift 4文本字段中用下划线替换空格

时间:2018-02-13 18:44:49

标签: ios swift uitextfield

我的用户注册屏幕中有一个文本字段; 用户名

为了避免用户将此字段留空 - 并且为了方便他们使用简单地结合其姓氏和姓氏的用户名 - 我目前有一个 IBAction ,当" 编辑完成"从小写的全名中取值。

@IBAction func fullNameEditingEnded(_ sender: Any) {
    let userName = fullnameTextfield.text?.lowercased()
    usernameTextfield.text = userName
    }

我想用下划线替换空格。这样做的最佳方法是什么?它是for循环还是更简单?

1 个答案:

答案 0 :(得分:3)

尝试这一点最好修剪端部空间,以便不能用_

替换
let aString = "first last"
let newString = aString.replacingOccurrences(of: " ", with: "_")
@IBAction func fullNameEditingEnded(_ sender: Any) {
    let userName = fullnameTextfield.text?.lowercased()
    usernameTextfield.text = userName.replacingOccurrences(of: " ", with: "_")
}