SwiftyJD SwiftyJD - 5 months ago 19
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)!

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

//Text
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.

Answer

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

class ViewController: UIViewController, UITextFieldDelegate {

  @IBOutlet var textField: CustomTextField!

  override func viewDidLoad() {
    super.viewDidLoad()

    textField.placeholder = "Some text..."
  }

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