Last active
May 9, 2022 13:18
Add placeholder text to UITextView in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TextView: UITextView { | |
override init(frame: CGRect, textContainer: NSTextContainer?) { | |
super.init(frame: frame, textContainer: textContainer) | |
commonInit() | |
} | |
required init?(coder: NSCoder) { | |
super.init(coder: coder) | |
} | |
override func awakeFromNib() { | |
super.awakeFromNib() | |
commonInit() | |
} | |
override func prepareForInterfaceBuilder() { | |
super.prepareForInterfaceBuilder() | |
commonInit() | |
} | |
private lazy var placeholderLabel: UILabel = { | |
let label = UILabel() | |
label.lineBreakMode = .byWordWrapping | |
label.numberOfLines = 0 | |
addSubview(label) | |
label.snp.makeConstraints { | |
$0.edges.equalToSuperview() | |
} | |
return label | |
}() | |
var placeholderText: String? { | |
get { placeholderLabel.text } | |
set { | |
placeholderLabel.text = newValue | |
setPlaceholderLabelHidden() | |
} | |
} | |
var placeholderTextColor: UIColor? { | |
get { placeholderLabel.textColor } | |
set { placeholderLabel.textColor = newValue } | |
} | |
override var text: String! { | |
didSet { | |
setPlaceholderLabelHidden() | |
} | |
} | |
override var textColor: UIColor? { | |
didSet { | |
tintColor = textColor | |
} | |
} | |
override var textAlignment: NSTextAlignment { | |
didSet { | |
placeholderLabel.textAlignment = textAlignment | |
} | |
} | |
override var font: UIFont? { | |
didSet { | |
placeholderLabel.font = font | |
} | |
} | |
override var backgroundColor: UIColor? { | |
didSet { | |
placeholderLabel.backgroundColor = backgroundColor | |
} | |
} | |
func commonInit() { | |
textContainerInset = .zero | |
textContainer.lineFragmentPadding = 0 | |
NotificationCenter.default.addObserver(forName: UITextView.textDidChangeNotification, object: nil, queue: nil) { [weak self] _ in | |
guard let self = self else { return } | |
self.setPlaceholderLabelHidden() | |
} | |
} | |
deinit { | |
NotificationCenter.default.removeObserver(self) | |
} | |
private func setPlaceholderLabelHidden() { | |
placeholderLabel.isHidden = (placeholderText ?? "").isEmpty || !text.isEmpty | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment