Assign xib to the UIView in Swift
for Swift 4
extension UIView { class func loadFromNibNamed(nibNamed: String, bundle: Bundle? = nil) -> UIView? { return UINib( nibName: nibNamed, bundle: bundle ).instantiate(withOwner: nil, options: nil)[0] as? UIView }}
for Swift 3
You could create an extension on UIView:
extension UIView { class func loadFromNibNamed(nibNamed: String, bundle: NSBundle? = nil) -> UIView? { return UINib( nibName: nibNamed, bundle: bundle ).instantiateWithOwner(nil, options: nil)[0] as? UIView }}
Note: Using UINib is faster because it does caching for you.
Then you can just do:
ViewDetailItem.loadFromNibNamed("ViewBtnWishList")
And you will be able to reuse that method on any view.
This worked for me.
override func awakeAfterUsingCoder(aDecoder: NSCoder) -> AnyObject? { if self.subviews.count == 0 { return loadNib() } return self}private func loadNib() -> YourCustomView { return NSBundle.mainBundle().loadNibNamed("YourCustomViewNibName", owner: nil, options: nil)[0] as YourCustomView}
Tested in Xcode 7 beta 4 , Swift 2.0 . The following code will assign xib to the UIView
.You can use this custom xib view in storyboard and access the IBOutlet
object also.
import UIKit@IBDesignable class SimpleCustomView:UIView{ var view:UIView!; @IBOutlet weak var lblTitle: UILabel! @IBInspectable var lblTitleText : String? { get{ return lblTitle.text; } set(lblTitleText) { lblTitle.text = lblTitleText!; } } override init(frame: CGRect) { super.init(frame: frame) loadViewFromNib () } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) loadViewFromNib () } func loadViewFromNib() { let bundle = NSBundle(forClass: self.dynamicType) let nib = UINib(nibName: "SimpleCustomView", bundle: bundle) let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView view.frame = bounds view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] self.addSubview(view); }}
Access customview programatically
self.customView = SimpleCustomView(frame: CGRectMake(100, 100, 200, 200)) self.view.addSubview(self.customView!);
Source code - https://github.com/karthikprabhuA/CustomXIBSwift