Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Assuming .xib name is the same as class name
- extension UIView {
- func nibView<T>(for: T.Type) -> UIView? {
- let nib = UINib(nibName: String(describing: T.self), bundle: nil)
- let view = nib.instantiate(withOwner: self, options: nil).first as? UIView
- return view
- }
- func addNibView<T>(from: T.Type) -> UIView? {
- guard let nibView = nibView(for: T.self) else{ return nil }
- addSubview(nibView)
- nibView.frame = bounds
- return nibView
- }
- }
- // To Use
- class CustomView: UIView {
- override init(frame: CGRect) {
- super.init(frame: frame)
- commonInit()
- }
- required init?(coder aDecoder: NSCoder) {
- super.init(coder: aDecoder)
- commonInit()
- }
- private func commonInit() {
- guard let view = addNibView(from: CustomView.self) else { return }
- // Do stuff with view
- // view.layer.cornerRadius = Constants.PRIMARY_CORNER_RADIUS
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement