![](/img/trans.png)
[英]How to add image and text in UITextField as placeholder in center in swift
[英]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"
textField.text = textField.text! + "@gmail.com"
-将@ gmail.com添加到您的字符串中
2: textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.beginningOfDocument)
-当用户点击textField时,将光标置于开头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.