Skip to content

Instantly share code, notes, and snippets.

@gfpacheco
Created January 11, 2016 19:43
Show Gist options
  • Save gfpacheco/9836f99a7ea32f5df811 to your computer and use it in GitHub Desktop.
Save gfpacheco/9836f99a7ea32f5df811 to your computer and use it in GitHub Desktop.
class PlaceholderTextView: UIView, UITextViewDelegate {
private var textView: UITextView!
private var isShowingPlaceholder = false
var placeholder = "" {
didSet {
showPlaceholderIfNeeded()
}
}
var text: String {
get {
return isShowingPlaceholder ? "" : textView.text
}
set {
hidePlaceholderIfNeeded()
textView.text = newValue
showPlaceholderIfNeeded()
}
}
var textColor = UIColor.blackColor() {
didSet {
if !isShowingPlaceholder {
textView.textColor = textColor
}
}
}
// Add textView property setter as needed
var font: UIFont? {
get { return textView.font }
set { textView.font = newValue }
}
convenience init() {
self.init(frame: CGRectZero)
textView = addSubview(UITextView()) { view in
view.delegate = self
view.snp_makeConstraints { make in
make.edges.equalTo(self)
}
}
}
private func showPlaceholderIfNeeded() {
if text == "" || isShowingPlaceholder {
isShowingPlaceholder = true
textView.textColor = UIColor.lightGrayColor()
textView.text = placeholder
}
}
private func hidePlaceholderIfNeeded() {
if isShowingPlaceholder {
isShowingPlaceholder = false
textView.text = ""
textView.textColor = textColor
}
}
func textViewDidBeginEditing(textView: UITextView) {
hidePlaceholderIfNeeded()
}
func textViewDidEndEditing(textView: UITextView) {
showPlaceholderIfNeeded()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment