UITextView
Placeholder
iOS Development
Swift
Mobile App Development

Placeholder in UITextView

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction to the Placeholder in UITextView

In iOS development, the UITextView is a fundamental component used for displaying and editing multiline text. Unlike the UITextField, which automatically supports placeholders, UITextView lacks this feature natively. Nevertheless, developers often need to implement placeholder text within UITextView to enhance user experience, providing guidance on what information or form of data the user is expected to enter.

Implementing a Placeholder in UITextView

Since UITextView does not provide built-in support for placeholders, a common practice is to implement this using a UILabel. This UILabel is superimposed over the UITextView, and it becomes hidden when the user types. We'll walk through a simple implementation.

Creating a Custom UITextView with a Placeholder

Below is an example of how you can implement a UITextView with a placeholder:

swift
1import UIKit
2
3class PlaceholderTextView: UITextView {
4    
5    private var placeholderLabel: UILabel = UILabel()
6    
7    var placeholder: String? {
8        didSet {
9            placeholderLabel.text = placeholder
10            setNeedsLayout()
11        }
12    }
13    
14    override var text: String! {
15        didSet {
16            textDidChange()
17        }
18    }
19    
20    override init(frame: CGRect, textContainer: NSTextContainer?) {
21        super.init(frame: frame, textContainer: textContainer)
22        setup()
23    }
24    
25    required init?(coder: NSCoder) {
26        super.init(coder: coder)
27        setup()
28    }
29    
30    private func setup() {
31        NotificationCenter.default.addObserver(self,
32                                               selector: #selector(textDidChange),
33                                               name: UITextView.textDidChangeNotification,
34                                               object: nil)
35        
36        placeholderLabel.textColor = .lightGray
37        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
38        addSubview(placeholderLabel)
39        
40        NSLayoutConstraint.activate([
41            placeholderLabel.topAnchor.constraint(equalTo: topAnchor, constant: 8),
42            placeholderLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 5)
43        ])
44    }
45    
46    @objc private func textDidChange() {
47        placeholderLabel.isHidden = !text.isEmpty
48    }
49    
50    deinit {
51        NotificationCenter.default.removeObserver(self,
52                                                  name: UITextView.textDidChangeNotification,
53                                                  object: nil)
54    }
55}

Explanation

  1. UILabel for Placeholder: A UILabel is added as a subview to act as the placeholder. It's styled to mimic placeholder behavior and set with a light gray color.
  2. Listening to Text Changes: The UITextView sets up a notification observer for UITextView.textDidChangeNotification to hide or show the placeholder label.
  3. Dynamic Updates: Whenever the text changes, the textDidChange method checks if the UITextView is empty to decide whether to hide the placeholder label.
  4. Constraints for Label: Constraints ensure that the placeholder label is correctly positioned inside the UITextView. These constraints are subtle adjustments for visual alignment.
  5. Placeholder Setter: The placeholder property shows its value in the UILabel, and updates when changed.

Enhancing Placeholder Functionality

While the basic implementation provides the core functionality needed for a placeholder, developers may seek to extend and customize this further.

Placeholder Styling

Custom styling options can be added to make the placeholder more appealing or consistent with app design:

swift
1func setPlaceholderFont(_ font: UIFont) {
2    placeholderLabel.font = font
3}
4
5func setPlaceholderColor(_ color: UIColor) {
6    placeholderLabel.textColor = color
7}

Placeholder Displacement

If there are paddings or insets in UITextView, adjust the UILabel placement accordingly to ensure optimal alignment:

swift
1override func layoutSubviews() {
2    super.layoutSubviews()
3    placeholderLabel.frame.origin.y = textContainerInset.top
4    placeholderLabel.frame.origin.x = textContainerInset.left + 5  // Additional inset
5}

Placeholder Multiline Capability

For cases where the placeholder can take multiple lines, ensure the UILabel accommodates this:

swift
placeholderLabel.numberOfLines = 0

Overview Table of UITextView Placeholder

Here's a summary of key aspects concerning placeholder implementation in UITextView:

ComponentDescription
UILabelUsed to display placeholder text
TextChange NotificationObserves text changes to toggle placeholder visibility
ConstraintsAlign UILabel within UITextView
CustomizationFont and color can be customized as needed
Line BreaksMultiline support through numberOfLines
Observer CleanupNecessary for memory management

Conclusion

Adding a placeholder to a UITextView is essential for many iOS applications, particularly those involving forms or data entry. While not built-in, the workaround using UILabel provides a flexible solution, allowing developers control over appearance and behavior. By expanding upon this basic implementation through customization and styling, developers can enhance user interfaces and improve app usability significantly.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.