Skip to content

Instantly share code, notes, and snippets.

@kellyhuberty
Last active December 9, 2019 17:04
Show Gist options
  • Save kellyhuberty/e797836b59c71c36791b25726eecbf2b to your computer and use it in GitHub Desktop.
Save kellyhuberty/e797836b59c71c36791b25726eecbf2b to your computer and use it in GitHub Desktop.
UITextView with placeholder text
class PlaceholderTextView: UITextView {
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func becomeFirstResponder() -> Bool {
let isFirstResponder = super.becomeFirstResponder()
removePlaceholderIfNeeded()
return isFirstResponder
}
override func resignFirstResponder() -> Bool {
addPlaceholderIfNeeded()
return super.resignFirstResponder()
}
var placeholderText: String? {
didSet {
addPlaceholderIfNeeded()
}
}
override var text: String? {
get {
if isPlaceholding {
return ""
}
return super.text
}
set {
removePlaceholderIfNeeded()
super.text = newValue
addPlaceholderIfNeeded()
}
}
var isPlaceholding: Bool = false
private func addPlaceholderIfNeeded() {
if super.text == nil || super.text == "" {
addPlaceholder()
}
}
private func removePlaceholderIfNeeded() {
if isPlaceholding {
removePlaceholder()
}
}
private func addPlaceholder() {
guard let placeholderText = placeholderText else {
return
}
self.textColor = Color.lightText
super.text = placeholderText
isPlaceholding = true
}
private func removePlaceholder() {
self.textColor = .black
super.text = ""
isPlaceholding = false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment