Introduction to tutorial – set placeholder to UITextView:
Follow the below steps to learn how to set placeholder to UITextView in swift4, swift3 or swift language.
Step1: Create a single view application project and name it “UITextViewPlaceholder”. Open “Main.storyboard” and drag UITextView to UIView of viewcontroller.
Step4: Attach IBOutlet to UITextView in “Main.Storyboard”.
Step5: In “ViewController.siwft”, inside ‘viewDidLoad’ function set text that will act as placeholder to UITextVie. We will set its textcolor and font so that it looks like a placeholder. Also we will set UITextView delegate.
Step6: If you run the app at this point, you will see UITextView displaying placeholder text.
If you type now, you won’t see placeholder stays there and text is getting appended to it. In order to remove placeholder as soon as use starts typing we need to take advantage of UITextView delegates methods.
Step7: Implement below code, here we are using UITextView delegate methods.
textViewDidBeginEditing
In this delegate method, we detected if our UITextView begins editing and if the text matches to our placeholder text then set it’s text to empty string. Also we change textcolor and font so that user feels that he is writing and its not the placeholder which grows.
shouldChangeTextIn
This delegate method is used so that we can dismiss keyboard. As soon as user hits Done button of keyboard we detected new line as UITextView append new line (n) when user presses done or return key of keyboard (default implementation by iOS).
textViewDidEndEditing
In this delegate method, we do exactly opposite of what we done in first delegate method (textViewDidBeginEditing). Here, we detected if UITextView text is empty or blank then we set placeholder text, font, textcolor to it.
Run your app now and you will see placeholder for UITextView is working perfectly. Below are the screen shots of the output
Where to go from here:
UITextView Placeholder swift source code