我正在尝试在 Swift 项目中重用 xib 中的组件,但我使用的是 Objective C 逻辑。因此,子类化 View 并加载 xib,然后在 View Controller 中实例化自定义 View 。
将代码翻译成 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];
任何正确方向的评论都会受到赞赏。
最佳答案
不能 100% 确定您的 OBJ-C 代码是否确实有效,但很可能不会。
您必须意识到此 [[NSBundle mainBundle] loadNibNamed:@"yourXib"Owner:self options:nil];
始终返回 IB xib 文件中的对象数组。据我所知,实际上您没有将此对象分配给任何地方。
此实现的问题可能是可以从边界获取的框架。
如果我们假设 IB 对象中只有一个对象,则此代码有效。
private func commonInit()
{
var nibView = NSBundle.mainBundle().loadNibNamed("mainBar", owner: self, options: nil)[0] as UIView
nibView.frame = self.bounds;
self.addSubview(nibView)
}
关于ios - 从 Swift 中的 View 子类加载 xib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26617242/