Created
February 10, 2018 19:21
-
-
Save kobeumut/4f321b86eee9af039e2015041882d188 to your computer and use it in GitHub Desktop.
Add Placeholder Swift 4 - iOS
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
| import UIKit | |
| extension UITextView: UITextViewDelegate { | |
| override open var bounds: CGRect { | |
| didSet { | |
| self.resizePlaceholder() | |
| } | |
| } | |
| public var placeholder: String? { | |
| get { | |
| var placeholderText: String? | |
| if let placeholderLbl = self.viewWithTag(50) as? UILabel { | |
| placeholderText = placeholderLbl.text | |
| } | |
| return placeholderText | |
| } | |
| set { | |
| if let placeholderLbl = self.viewWithTag(50) as! UILabel? { | |
| placeholderLbl.text = newValue | |
| placeholderLbl.sizeToFit() | |
| } else { | |
| self.addPlaceholder(newValue!) | |
| } | |
| } | |
| } | |
| public func textViewDidChange(_ textView: UITextView) { | |
| if let placeholderLbl = self.viewWithTag(50) as? UILabel { | |
| placeholderLbl.isHidden = self.text.characters.count > 0 | |
| } | |
| } | |
| private func resizePlaceholder() { | |
| if let placeholderLbl = self.viewWithTag(50) as! UILabel? { | |
| let x = self.textContainer.lineFragmentPadding | |
| let y = self.textContainerInset.top - 2 | |
| let width = self.frame.width - (x * 2) | |
| let height = placeholderLbl.frame.height | |
| placeholderLbl.frame = CGRect(x: x, y: y, width: width, height: height) | |
| } | |
| } | |
| private func addPlaceholder(_ placeholderText: String) { | |
| let placeholderLbl = UILabel() | |
| placeholderLbl.text = placeholderText | |
| placeholderLbl.sizeToFit() | |
| placeholderLbl.font = self.font | |
| placeholderLbl.textColor = UIColor.lightGray | |
| placeholderLbl.tag = 50 | |
| placeholderLbl.isHidden = self.text.characters.count > 0 | |
| self.addSubview(placeholderLbl) | |
| self.resizePlaceholder() | |
| self.delegate = self | |
| } | |
| } |
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
| let textView = UITextView() | |
| textView.placeholder = "Your Messaging..." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment