Skip to content

Instantly share code, notes, and snippets.

@wata
Last active May 9, 2022 13:18
Show Gist options
  • Save wata/81d1702f4828a85719e48f934c0241b8 to your computer and use it in GitHub Desktop.
Save wata/81d1702f4828a85719e48f934c0241b8 to your computer and use it in GitHub Desktop.
Add placeholder text to UITextView in Swift
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