Created
March 7, 2019 12:14
-
-
Save jamesgathu/7c5725bf53471d6f275e4e6cbd0f3f1e to your computer and use it in GitHub Desktop.
Adding Placeholder to UITextView
This file contains 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
@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