ios - 从 Swift 中的 View 子类加载 xib

标签 ios uiview swift xib

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

相关文章:

ios - 来自 App Scoped ID with Objective-C 的 Facebook 个人资料图片和名称

ios - 2018 年 4 月,iOS 11 和新应用提交

ScrollView 中嵌入 View 的 iOS 7 自动布局

ios - 用 CAShapeLayer 实现绘制渐变圆弧

ios - 停止从 webview 进行深层链接导航

ios - 当应用程序移至后台时如何使 URLSession 工作

ios - 在 UIView 内旋转 UIImageView 的奇怪行为

iOS9:在另一个以编程方式添加的 View 中居中以编程方式添加的 View

ios - Swift 协议(protocol)委托(delegate)未被解雇

json - 由于信号 : Segmentation fault: 11 due to TableViewController?,命令失败