You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.8 KiB

5 years ago
  1. /*********************************************
  2. *
  3. * This code is under the MIT License (MIT)
  4. *
  5. * Copyright (c) 2016 AliSoftware
  6. *
  7. *********************************************/
  8. import UIKit
  9. // MARK: Protocol Definition
  10. /// Make your UIView subclasses conform to this protocol when:
  11. /// * they *are* NIB-based, and
  12. /// * this class is used as the XIB's File's Owner
  13. ///
  14. /// to be able to instantiate them from the NIB in a type-safe manner
  15. public protocol NibOwnerLoadable: class {
  16. /// The nib file to use to load a new instance of the View designed in a XIB
  17. static var nib: UINib { get }
  18. }
  19. // MARK: Default implementation
  20. public extension NibOwnerLoadable {
  21. /// By default, use the nib which have the same name as the name of the class,
  22. /// and located in the bundle of that class
  23. static var nib: UINib {
  24. return UINib(nibName: String(describing: self), bundle: Bundle(for: self))
  25. }
  26. }
  27. // MARK: Support for instantiation from NIB
  28. public extension NibOwnerLoadable where Self: UIView {
  29. /**
  30. Adds content loaded from the nib to the end of the receiver's list of subviews and adds constraints automatically.
  31. */
  32. func loadNibContent() {
  33. let layoutAttributes: [NSLayoutConstraint.Attribute] = [.top, .leading, .bottom, .trailing]
  34. for case let view as UIView in Self.nib.instantiate(withOwner: self, options: nil) {
  35. view.translatesAutoresizingMaskIntoConstraints = false
  36. self.addSubview(view)
  37. NSLayoutConstraint.activate(layoutAttributes.map { attribute in
  38. NSLayoutConstraint(
  39. item: view, attribute: attribute,
  40. relatedBy: .equal,
  41. toItem: self, attribute: attribute,
  42. multiplier: 1, constant: 0.0
  43. )
  44. })
  45. }
  46. }
  47. }
  48. /// Swift < 4.2 support
  49. #if !(swift(>=4.2))
  50. private extension NSLayoutConstraint {
  51. typealias Attribute = NSLayoutAttribute
  52. }
  53. #endif