Guest User

Untitled

a guest
Feb 23rd, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. import UIKit
  2.  
  3. extension UITextView: UITextViewDelegate {
  4. override open var bounds: CGRect {
  5. didSet {
  6. self.resizePlaceholder()
  7. }
  8. }
  9.  
  10. public var placeholder: String? {
  11. get {
  12. var placeholderText: String?
  13.  
  14. if let placeholderLbl = self.viewWithTag(50) as? UILabel {
  15. placeholderText = placeholderLbl.text
  16. }
  17.  
  18. return placeholderText
  19. }
  20. set {
  21. if let placeholderLbl = self.viewWithTag(50) as! UILabel? {
  22. placeholderLbl.text = newValue
  23. placeholderLbl.sizeToFit()
  24. } else {
  25. self.addPlaceholder(newValue!)
  26. }
  27. }
  28. }
  29.  
  30. public func textViewDidChange(_ textView: UITextView) {
  31. if let placeholderLbl = self.viewWithTag(50) as? UILabel {
  32. placeholderLbl.isHidden = self.text.characters.count > 0
  33. }
  34. }
  35.  
  36. private func resizePlaceholder() {
  37. if let placeholderLbl = self.viewWithTag(50) as! UILabel? {
  38. let x = self.textContainer.lineFragmentPadding
  39. let y = self.textContainerInset.top - 2
  40. let width = self.frame.width - (x * 2)
  41. let height = placeholderLbl.frame.height
  42.  
  43. placeholderLbl.frame = CGRect(x: x, y: y, width: width, height: height)
  44. }
  45. }
  46.  
  47. private func addPlaceholder(_ placeholderText: String) {
  48. let placeholderLbl = UILabel()
  49.  
  50. placeholderLbl.text = placeholderText
  51. placeholderLbl.sizeToFit()
  52.  
  53. placeholderLbl.font = self.font
  54. placeholderLbl.textColor = UIColor.lightGray
  55. placeholderLbl.tag = 50
  56.  
  57. placeholderLbl.isHidden = self.text.characters.count > 0
  58.  
  59. self.addSubview(placeholderLbl)
  60. self.resizePlaceholder()
  61. self.delegate = self
  62. }
  63. }
Add Comment
Please, Sign In to add comment