我试图让文本字段在用户开始输入时始终以“@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)
- 当用户点击 textField 时将光标放在开头。
关于ios - 如何在 UItextfield 中快速添加永久占位符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48843825/