I’m trying to reuse a component from a xib in a Swift project, but I’m using Objective C logic. Thus, subclassing a view and loading the xib, then instantiating the custom view in the view controller.
Translating the code into Swift is not producing the results expected.
CustomView.swift:
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fatalError("Error detected")
self.commonInit()
}
private func commonInit() {
NSBundle.mainBundle().loadNibNamed("mainBar", owner: self, options: nil)
self.addSubview(self)
}
viewController.swift:
var bottomBar : customView = customView(frame: CGRect(x: 0, y: 250, width: 250, height: 70))
//bottomBar.backgroundColor = UIColor.redColor()
self.view.addSubview(bottomBar)
Objective-C I used as a reference:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self baseInit];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
[[NSBundle mainBundle] loadNibNamed:@"yourXib" owner:self options:nil];
[self addSubview:self.view];
}
return self;
}
CustomView * myView = [CustomView alloc]init];
[self.view addSubView:myView];
Any comment in the right direction is appreciated.