Skip to content

Instantly share code, notes, and snippets.

@jamesgathu
Created March 7, 2019 12:14
Show Gist options
  • Save jamesgathu/7c5725bf53471d6f275e4e6cbd0f3f1e to your computer and use it in GitHub Desktop.
Save jamesgathu/7c5725bf53471d6f275e4e6cbd0f3f1e to your computer and use it in GitHub Desktop.
Adding Placeholder to UITextView
@IBDesignable
class PlaceHolderTextView: UITextView {
@IBInspectable var placeholder: String = "" {
didSet{
updatePlaceHolder()
}
}
@IBInspectable var placeholderColor: UIColor = UIColor.gray {
didSet {
updatePlaceHolder()
}
}
private var originalTextColor = UIColor.darkText
private var originalText: String = ""
private func updatePlaceHolder() {
if self.text == "" || self.text == placeholder {
self.text = placeholder
self.textColor = placeholderColor
if let color = self.textColor {
self.originalTextColor = color
}
self.originalText = ""
} else {
self.textColor = self.originalTextColor
self.originalText = self.text
}
}
override func becomeFirstResponder() -> Bool {
let result = super.becomeFirstResponder()
self.text = self.originalText
self.textColor = self.originalTextColor
return result
}
override func resignFirstResponder() -> Bool {
let result = super.resignFirstResponder()
updatePlaceHolder()
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment