Add placeholder to UITextView Swift

There are instances where we need to use UITextView as a multi-line text field in our app. The UITextView does not provide a placeholder property like the UITextField. So, in order to achieve this we need to implement the following methods in our UIViewController:

class DemoVC: UIViewController, UITextViewDelegate {

//hook this to the storyboard UITextView
@IBOutlet weak var descriptionTxtView: UITextView!

func textViewDidBeginEditing(_ textView: UITextView) {
        if descriptionTxtView.text == "Add description..." {
            descriptionTxtView.text = ""
            descriptionTxtView.textColor = UIColor.black
        }
    }
    
    func textViewDidEndEditing(_ textView: UITextView) {
        if descriptionTxtView.text == "" {
            descriptionTxtView.text = "Add description..."
            descriptionTxtView.textColor = #colorLiteral(red: 0.4922404289, green: 0.7722371817, blue: 0.4631441236, alpha: 1)
        }
    }

}

Please note in the above code that the View Controller class also conforms to the UITextViewDelegate. All of the methods in the protocol are optional, however use them to adjust the text as needed.

The above code is implemented using Swift 4.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.