Last active
January 9, 2018 05:30
-
-
Save lamlv2305/5e0371d28f717e58c2019fffa5028418 to your computer and use it in GitHub Desktop.
Using xibview with storyboard. Do not forget to set "File's Owner -> Custom Class" in your xib file.
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
import UIKit | |
@IBDesignable | |
class XibView: UIView { | |
@IBInspectable var nibName: String? | |
private(set) var contentView: UIView? | |
override func awakeFromNib() { | |
super.awakeFromNib() | |
contentView = xibSetup(nibName: nibName) | |
} | |
override func prepareForInterfaceBuilder() { | |
super.prepareForInterfaceBuilder() | |
contentView = xibSetup(nibName: nibName) | |
contentView?.prepareForInterfaceBuilder() | |
} | |
} | |
extension UIView { | |
func loadView(fromNib name: String) -> UIView? { | |
let bundle = Bundle(for: type(of: self)) | |
let nib = UINib(nibName: name, bundle: bundle) | |
return nib.instantiate(withOwner: self, options: nil).first as? UIView | |
} | |
func xibSetup(nibName: String?) -> UIView { | |
let nibName = nibName ?? String(describing: type(of: self)) | |
guard let view = loadView(fromNib: nibName) else { | |
fatalError("Couldn't load nib from nibName: \(nibName)") | |
} | |
view.frame = bounds | |
view.autoresizingMask = [.flexibleWidth, .flexibleHeight] | |
addSubview(view) | |
return view | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment