Last active
August 25, 2020 13:19
-
-
Save AmirHossein/f091f61ab93c40dd5054ddedefdb8607 to your computer and use it in GitHub Desktop.
Add 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
class UITextViewWithPlaceholder: UITextView, UITextViewDelegate { | |
private var placeholderLabel: UILabel?; | |
required init?(coder: NSCoder){ | |
super.init(coder: coder) | |
self.delegate = self; | |
} | |
func setPlaceholder(text: String, color: UIColor = Constants.View.whiteColor.withAlphaComponent(0.5)) { | |
if (self.placeholderLabel == nil) { | |
let placeholderLabel = UILabel(); | |
placeholderLabel.text = text; | |
placeholderLabel.font = self.font; | |
placeholderLabel.textColor = color; | |
placeholderLabel.sizeToFit() | |
placeholderLabel.frame.origin = CGPoint(x: 5, y: (placeholderLabel.font?.pointSize)! / 2) | |
placeholderLabel.isHidden = self.text == nil || !self.text!.isEmpty | |
self.placeholderLabel = placeholderLabel; | |
self.addSubview(self.placeholderLabel!) | |
} | |
} | |
func textViewDidChange(_ textView: UITextView) { | |
let view = textView as! UITextViewWithPlaceholder; | |
if (view.placeholderLabel != nil) { | |
view.placeholderLabel!.isHidden = view.text == nil || !view.text!.isEmpty | |
} | |
} | |
} | |
// Usage | |
class ViewController: UIViewController { | |
@IBOutlet weak var textView: UITextViewWithPlaceholder! | |
override func viewDidLoad() { | |
super.viewDidLoad(); | |
self.textView.setPlaceholder(text: "Placeholder..."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment