Created
January 11, 2016 19:43
-
-
Save gfpacheco/9836f99a7ea32f5df811 to your computer and use it in GitHub Desktop.
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: 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