Last active
March 12, 2019 04:13
-
-
Save Shinolr/e7d35518ddfe40d4999943523e2ffa57 to your computer and use it in GitHub Desktop.
Xib file reusable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SameNameWithXibFile: UIView, XibReusable { | |
var contentView: UIView! | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
xibSetup() | |
} | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
xibSetup() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol XibReusable: AnyObject { | |
var contentView: UIView! { get set } | |
func xibSetup() | |
} | |
extension XibReusable where Self: UIView { | |
func xibSetup() { | |
contentView = loadViewFromNib() | |
contentView.frame = bounds | |
contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight] | |
addSubview(contentView) | |
} | |
func loadViewFromNib() -> UIView { | |
let bundle = Bundle(for: type(of: self)) | |
let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle) | |
let view = nib.instantiate(withOwner: self, options: nil).first as? UIView | |
return view! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment