6
votes

Is there an up to date swift solution for making a UITextField placeholder disappear, or the cursor to be brought to the front as soon as a user clicks in the field, rather than when they start typing. I tried some of the solutions from older posts, and I tried the code below, but it doesn't seem to have the desired effect. Any help much appreciated.

class LogInViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var userTextField: UITextField! 
// the placeholder text is set in IB, with clear Button set to Appears while editing, and clear when editing begins button checked. 

func textFieldDidBeginEditing(textField: UITextField) {
    userTextField.placeholder = nil
    passwordTextField.placeholder = nil
}
}

This worked for me:

adding userTextField.delegate = self to view did load. // thanks I missed that

 func textFieldDidBeginEditing(textField: UITextField) {

    if userTextField.isFirstResponder() == true {
        userTextField.placeholder = nil
    }
}
5

5 Answers

4
votes

If you have more than one TextField

1) Add String variable to your class

class YourViewController : UIViewController {

    var placeHolder = ""

2) Add UITextFieldDelegate

extension YourViewController : UITextFieldDelegate {

func textFieldDidBeginEditing(_ textField: UITextField) {
    placeHolder = textField.placeholder ?? ""
    textField.placeholder = ""
}

func textFieldDidEndEditing(_ textField: UITextField) {
    if textField.placeholder == ""{
    textField.placeholder = placeHolder
    }
}
3
votes

First thing make sure you set the delegate of the text field either from storyboard or set it in the viewDidLoad()

And change your code to this

userTextField.placeholder = ""
passwordTextField.placeholder = ""
1
votes

In Swift 3

func textFieldDidBeginEditing(_ textField: UITextField) {
    if loginTextField.isFirstResponder == true {
        loginTextField.placeholder = ""
    }
}
1
votes

Create a subclass of UITextField:

class CustomTextField: UITextField {

    private var placeholderBackup: String?

    override func becomeFirstResponder() -> Bool {
        placeholderBackup = placeholder
        placeholder = nil
        return super.becomeFirstResponder()
    }

    override func resignFirstResponder() -> Bool {
        placeholder = placeholderBackup
        return super.resignFirstResponder()
    }
}
0
votes

if you wanna have an invisible placeholder (e.g. creating your own custom text field), you can just override this method:

public override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
        return .zero
}