I have some strange problem with loading xib file in swift project. It\'s so frustrating because I already know how to do it in Obj-C. But since swift is swift so you can\'t
This works for me:
class IconTextField: UITextField {
@IBOutlet weak var view: UIView!
@IBOutlet weak var test: UIButton!
required init(coder: NSCoder) {
super.init(coder: coder)
NSBundle.mainBundle().loadNibNamed("IconTextField", owner: self, options: nil)
self.addSubview(view)
assert(test != nil, "the button is conected just like it's supposed to be")
}
}
Once loadNibNamed:owner:options:
is called the view
and test
button are connected to the outlets as expected. Adding the nib's view self's subview hierarchy makes the nib's contents visible.
I prefer to load from nib, by implementing loadFromNib()
function in a protocol extension as follows:
(as explained here: https://stackoverflow.com/a/33424509/845027)
import UIKit
protocol UIViewLoading {}
extension UIView : UIViewLoading {}
extension UIViewLoading where Self : UIView {
// note that this method returns an instance of type `Self`, rather than UIView
static func loadFromNib() -> Self {
let nibName = "\(self)".characters.split{$0 == "."}.map(String.init).last!
let nib = UINib(nibName: nibName, bundle: nil)
return nib.instantiateWithOwner(self, options: nil).first as! Self
}
}
You can use this:
if let customView = Bundle.main.loadNibNamed("MyCustomView", owner: self, options: nil)?.first as? MyCustomView {
// Set your view here with instantiated customView
}