Add Placeholder to UITextField, how to set the placeholder text programmatically in swift?

让人想犯罪 __ 提交于 2019-12-05 13:50:12

问题


I'm pulling out a phone number from a database, and when the user begins editing in the text field to change that phone number I'd like to use the number I currently have in the database as the placeholder. Since this information changes with each user, how can I set it programmatically in swift?


回答1:


You need to get the phone number from your database first (convert them to String), then you set placeholder of your textField to that String, like so

 textField.placeholder = phoneNumberString



回答2:


Swift 3

If your textField has text, you need to first set text property to nil, then set placeholder text:

textField.text = nil
textField.placeholder = "My Placeholder Text"



回答3:


Important to note for anyone else reading this, setting placeholder text in the main.storyboard seems to nullify this solution, so I had to first clear out my placeholders in the storyboard before implementing this. Once that was done @Khuong and @Himanshu's answer worked perfectly.




回答4:


Apply this line of code in to View Did Load

new_Password.attributedPlaceholder =
            NSAttributedString(string: " New Password", attributes: [NSForegroundColorAttributeName : UIColor.white]) // new_Password : our text feild name



回答5:


Fetch your desired data from your database (Core data) and after converting it into string format... say phoneString

use this line to set this string as a placeholder text

phoneTextField.placeholder = phoneString



回答6:


Objective-C code:

[usernameText setPlaceholder:@"My Placeholder Text"];


来源:https://stackoverflow.com/questions/36995356/add-placeholder-to-uitextfield-how-to-set-the-placeholder-text-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!