【发布时间】:2014-12-24 09:12:22
【问题描述】:
我正在尝试在 Swift 项目中重用来自 xib 的组件,但我使用的是 Objective C 逻辑。因此,子类化视图并加载 xib,然后在 视图控制器中实例化 自定义视图。
将代码翻译成 Swift 并没有产生预期的结果。
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 我用作参考:
- (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];
感谢任何正确方向的评论。
【问题讨论】:
-
执行时swift代码有什么问题?
-
xib 没有加载到视图控制器中。