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

7

33

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?

Softspoken answered 3/5, 2016 at 3:58 Comment(0)
C
62

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
Compossible answered 3/5, 2016 at 4:6 Comment(0)
T
8

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"
Township answered 22/2, 2017 at 1:4 Comment(0)
S
5

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.

Softspoken answered 3/5, 2016 at 4:42 Comment(0)
T
2

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
Triny answered 3/5, 2016 at 4:18 Comment(0)
H
2

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
Holytide answered 25/1, 2018 at 5:25 Comment(1)
this is what worked for me, its very strange, to set placeHolder to empty string fieled?.attributedPlaceholder = NSAttributedString()Kickstand
G
0

Objective-C code:

[usernameText setPlaceholder:@"My Placeholder Text"];
Gerigerianna answered 23/2, 2018 at 20:40 Comment(0)
A
0

Just a note to say if you have changed your textfield's text and background colors programmatically, you can't do that with the placeholder text's colors and must set up an Attributed Placeholder instead. This is a problem if your device is in put in "dark mode" and are trying to make a non-dark mode screen by hand - you might not be able to see the placeholder!

Assemblage answered 23/12, 2019 at 21:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.