Last active
December 9, 2019 17:04
-
-
Save kellyhuberty/e797836b59c71c36791b25726eecbf2b to your computer and use it in GitHub Desktop.
UITextView with placeholder text
This file contains hidden or 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 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