SwiftyJD SwiftyJD - 4 months ago 16x
Swift Question

How to manually add UITextField placeholder text that disappears when clicked inside textfield?

I currently have a custom textfield so the storyboard way of adding placeholder text isn't working. Right now I'm using this code in viewDidLoad but when I click inside the textfield the placeholder text still remains.

usernameOrEmailTextField.text = "Username or email"
usernameOrEmailTextField.textColor = UIColor.whiteColor()

Is there a way to have the text disappear when the textfield is clicked so the user can type their own info for the textfield?

Here is my custom textfield:

class CustomTextField: UITextField{

required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!

self.layer.cornerRadius = 10.0;
self.layer.borderWidth = 0.75
self.layer.borderColor = UIColor.whiteColor().CGColor
self.backgroundColor = UIColor(white: 1, alpha: 0.0)

self.textColor = UIColor.whiteColor()
self.textAlignment = NSTextAlignment.Left


I tried using .placeholder instead of .text:

usernameOrEmailTextField.placeholder = "Username or email"
usernameOrEmailTextField.textColor = UIColor.whiteColor()

but the textfield appears to be blank.


You can use the delegate method textFieldShouldBeginEditing(textField:) for it:

class ViewController: UIViewController, UITextFieldDelegate {

  @IBOutlet var textField: CustomTextField!

  override func viewDidLoad() {

    textField.placeholder = "Some text..."

  func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
    textField.placeholder = ""
    return true