从Swift中的视图子类加载xib

时间:2014-10-28 19:49:13

标签: ios uiview swift xib

我正在尝试在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];

赞赏任何正确方向的评论。

2 个答案:

答案 0 :(得分:2)

不是百分之百确定你的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)
}

答案 1 :(得分:2)

你可以尝试这个

build.gradle