如何在 swift 的 UItextfield 中添加永久占位符?

How to add a permanent placeholder in a UItextfield for swift?

我试图让文本字段在用户开始输入时始终以“@gmail.com”结尾。因此,在对文本字段进行任何更改后,它总是会将该行附加到用户已经键入的任何内容,并且用户不应该能够删除它。

我试过使用 "shouldChangeCharactersIn" 函数,但似乎无法正常工作。

我这样做的原因是为了让用户能够理解我们只接受 gmail 帐户,并认为这是最好的方法,而不是试图解析字符串的最后 10 个字符来检查“ @gmail.com".

你应该这样做:

如果用户添加 @ 然后拒绝该部分,则控制:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField.tag == 0 {
        if string == "@" {
            return false
        }
    }
    return true
}

所以你基本上显示了它是 @gmail.com 的标签,用户在 textField 中添加了第一部分。

更新:
如果你真的想在 textField 中使用它:

func textFieldDidBeginEditing(_ textField: UITextField) {
        textField.text = textField.text! + "@gmail.com"

        textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.beginningOfDocument)
    }

此处分两部分:
1: textField.text = textField.text! + "@gmail.com" - 添加@gmail.com到你的字符串

2: textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.beginningOfDocument) - 当用户点击文本字段时将光标置于开头。