I've always used the loadNibNamed method for loading custom views into view controllers, but now i'm trying to avoid calling that method outside the custom view for making it more reusable so that if another person uses my custom view he only will need to instantiate the view without loadFromNib, for example:
var myView: MyView = MyView()
And adding this view to the view controller's view would be enough, the custom view will load the nib inside itself. I'm trying to do it in Swift, in ObjC I've found code like the one of this answer: UIView and initWithFrame and a NIB file. How can i get the NIB file loaded? But in swift I can't use the init used in the answer:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code.
//
[[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil];
[self addSubview:self.view];
}
return self;
}
I have this method and it ends with an infinite loop:
override init(frame: CGRect) {
super.init(frame: frame)
self.loadFromNibNamed("MyView")
}
I've also tried adding another view inside MyView as a IBOutlet like the other answer says and using all the inits:
@IBOutlet var view: UIView!
override init() {
super.init()
NSBundle.mainBundle().loadNibNamed("MediaPlayerView", owner: self, options: nil)
self.addSubview(self.view)
}
override init(frame: CGRect) {
super.init(frame: frame)
NSBundle.mainBundle().loadNibNamed("MediaPlayerView", owner: self, options: nil)
self.addSubview(self.view)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
NSBundle.mainBundle().loadNibNamed("MediaPlayerView", owner: self, options: nil)
self.addSubview(self.view)
}
But still got the error of the infinite loop.
I can't find a good solution to that and it's driving me crazy!! Somebody can help me please? Thanks!
MyView
orMediaPlayerView
, resp.? This could be the reason of the infinite loop, and I would guessinit(coder:)
as the cause. – clemens