SHARE
TWEET

Untitled

a guest Apr 22nd, 2019 73 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top