Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. // Assuming .xib name is the same as class name
  2.  
  3. extension UIView {
  4. func nibView<T>(for: T.Type) -> UIView? {
  5. let nib = UINib(nibName: String(describing: T.self), bundle: nil)
  6. let view = nib.instantiate(withOwner: self, options: nil).first as? UIView
  7. return view
  8. }
  9.  
  10. func addNibView<T>(from: T.Type) -> UIView? {
  11. guard let nibView = nibView(for: T.self) else{ return nil }
  12. addSubview(nibView)
  13. nibView.frame = bounds
  14. return nibView
  15. }
  16. }
  17.  
  18. // To Use
  19.  
  20. class CustomView: UIView {
  21.  
  22. override init(frame: CGRect) {
  23. super.init(frame: frame)
  24. commonInit()
  25. }
  26.  
  27. required init?(coder aDecoder: NSCoder) {
  28. super.init(coder: aDecoder)
  29. commonInit()
  30. }
  31.  
  32. private func commonInit() {
  33. guard let view = addNibView(from: CustomView.self) else { return }
  34. // Do stuff with view
  35. // view.layer.cornerRadius = Constants.PRIMARY_CORNER_RADIUS
  36. }
  37.  
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement