PlaceholderDesignable.swift 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //
  2. // Created by Jake Lin on 11/19/15.
  3. // Copyright © 2015 IBAnimatable. All rights reserved.
  4. //
  5. import UIKit
  6. public protocol PlaceholderDesignable: class {
  7. /**
  8. `color` within `::-webkit-input-placeholder`, `::-moz-placeholder` or `:-ms-input-placeholder`
  9. */
  10. var placeholderColor: UIColor? { get set }
  11. var placeholderText: String? { get set }
  12. }
  13. public extension PlaceholderDesignable where Self: UITextField {
  14. var placeholderText: String? { get { return "" } set {} }
  15. func configurePlaceholderColor() {
  16. let text = placeholder ?? placeholderText
  17. if let placeholderColor = placeholderColor, let placeholder = text {
  18. attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [.foregroundColor: placeholderColor])
  19. }
  20. }
  21. }
  22. public extension PlaceholderDesignable where Self: UITextView {
  23. func configure(placeholderLabel: UILabel, placeholderLabelConstraints: inout [NSLayoutConstraint]) {
  24. placeholderLabel.font = font
  25. placeholderLabel.textColor = placeholderColor
  26. placeholderLabel.textAlignment = textAlignment
  27. placeholderLabel.text = placeholderText
  28. placeholderLabel.numberOfLines = 0
  29. placeholderLabel.backgroundColor = .clear
  30. placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
  31. addSubview(placeholderLabel)
  32. update(placeholderLabel, using: &placeholderLabelConstraints)
  33. }
  34. func update(_ placeholderLabel: UILabel, using constraints: inout [NSLayoutConstraint]) {
  35. var format = "H:|-(\(textContainerInset.left + textContainer.lineFragmentPadding))-[placeholder]"
  36. var newConstraints = NSLayoutConstraint.constraints(withVisualFormat: format,
  37. options: [], metrics: nil,
  38. views: ["placeholder": placeholderLabel])
  39. format = "V:|-(\(textContainerInset.top))-[placeholder]"
  40. newConstraints += NSLayoutConstraint.constraints(withVisualFormat: format,
  41. options: [], metrics: nil,
  42. views: ["placeholder": placeholderLabel])
  43. let constant = -(textContainerInset.left + textContainerInset.right + textContainer.lineFragmentPadding * 2.0)
  44. newConstraints.append(NSLayoutConstraint(item: placeholderLabel,
  45. attribute: .width,
  46. relatedBy: .equal,
  47. toItem: self,
  48. attribute: .width,
  49. multiplier: 1.0,
  50. constant: constant))
  51. removeConstraints(constraints)
  52. addConstraints(newConstraints)
  53. constraints = newConstraints
  54. }
  55. }