Skip to content

Instantly share code, notes, and snippets.

@fewlinesofcode
Last active November 6, 2018 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fewlinesofcode/e395d5ea0f0e60634f80aab542a87946 to your computer and use it in GitHub Desktop.
Save fewlinesofcode/e395d5ea0f0e60634f80aab542a87946 to your computer and use it in GitHub Desktop.
The idea was to make the simplest possible solution which allows to use placeholders of different colors, resizes to placeholders size, will not overwrite a `delegate` meanwhile keeping all `UITextView` functions work as expected.
//
// Created by Oleksandr Glagoliev on 05/11/2018.
// Copyright © 2018 Oleksandr Glagoliev. All rights reserved.
//
import UIKit
class PlaceholderTextView: UITextView {
var placeholderColor: UIColor = .lightGray
var defaultTextColor: UIColor = .black
private var isShowingPlaceholder = false {
didSet {
if isShowingPlaceholder {
text = placeholder
textColor = placeholderColor
} else {
textColor = defaultTextColor
}
}
}
var placeholder: String? {
didSet {
isShowingPlaceholder = !hasText
}
}
@objc private func textViewDidBeginEditing(notification: Notification) {
textColor = defaultTextColor
if isShowingPlaceholder { text = nil }
}
@objc private func textViewDidEndEditing(notification: Notification) {
isShowingPlaceholder = !hasText
}
// MARK: - Construction -
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
NotificationCenter.default.addObserver(self, selector: #selector(textViewDidBeginEditing(notification:)), name: UITextView.textDidBeginEditingNotification, object: self)
NotificationCenter.default.addObserver(self, selector: #selector(textViewDidEndEditing(notification:)), name: UITextView.textDidEndEditingNotification, object: self)
}
// MARK: - Destruction -
deinit { NotificationCenter.default.removeObserver(self) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment