FillDesignable.swift 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. //
  2. // Created by Jake Lin on 12/5/15.
  3. // Copyright © 2015 IBAnimatable. All rights reserved.
  4. //
  5. import UIKit
  6. public protocol FillDesignable: class {
  7. var fillColor: UIColor? { get set }
  8. var predefinedColor: ColorType? { get set }
  9. var opacity: CGFloat { get set }
  10. }
  11. // MARK: - UIView
  12. public extension FillDesignable where Self: UIView {
  13. func configureFillColor() {
  14. configureFillColor(in: self)
  15. }
  16. func configureOpacity() {
  17. configureOpacity(in: self)
  18. }
  19. }
  20. // MARK: - UITableViewCell
  21. public extension FillDesignable where Self: UITableViewCell {
  22. func configureFillColor() {
  23. if let fillColor = fillColor {
  24. backgroundColor = fillColor
  25. contentView.backgroundColor = fillColor
  26. } else if let predefinedColor = predefinedColor?.color {
  27. backgroundColor = predefinedColor
  28. contentView.backgroundColor = predefinedColor
  29. }
  30. }
  31. }
  32. // MARK: - UICollectionViewCell
  33. public extension FillDesignable where Self: UICollectionViewCell {
  34. func configureFillColor() {
  35. if let fillColor = fillColor {
  36. backgroundColor = fillColor
  37. contentView.backgroundColor = fillColor
  38. } else if let predefinedColor = predefinedColor?.color {
  39. backgroundColor = predefinedColor
  40. contentView.backgroundColor = predefinedColor
  41. }
  42. }
  43. }
  44. // MARK: - Common
  45. extension FillDesignable {
  46. func configureFillColor(in view: UIView) {
  47. if let fillColor = fillColor {
  48. view.backgroundColor = fillColor
  49. } else if let predefinedColor = predefinedColor?.color {
  50. view.backgroundColor = predefinedColor
  51. }
  52. }
  53. func configureOpacity(in view: UIView) {
  54. guard !opacity.isNaN && opacity >= 0 && opacity <= 1 else {
  55. return
  56. }
  57. view.alpha = opacity
  58. // Make better performance
  59. view.isOpaque = opacity == 1
  60. }
  61. private func predefinedColor(string predefinedColor: String?) -> UIColor? {
  62. return ColorType(rawValue: predefinedColor ?? "")?.color
  63. }
  64. }