问题
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