[英]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.