Swift相当于[NSBundle bundleForClass:[self class]]

时间:2014-09-03 18:39:35

标签: swift

什么是下一个代码的快速等价物:

[NSBundle bundleForClass:[self class]]

我需要从测试包(JSON数据)加载资源

10 个答案:

答案 0 :(得分:200)

从未使用过,但我认为应该是这样:

Swift< = 2.x

NSBundle(forClass: self.dynamicType)

Swift 3.x

Bundle(for: type(of: self))

答案 1 :(得分:32)

斯威夫特3:

Bundle(for: type(of: self))

答案 2 :(得分:12)

我个人喜欢:

let bun = NSBundle(forClass: self.classForCoder)

答案 3 :(得分:9)

let bundle = NSBundle(forClass:object_getClass(self))

答案 4 :(得分:6)

在UIView子类的静态方法中,所选答案对我不起作用,但我发现了这个:

Bundle(for: self.classForCoder)

当您想要在测试目标中获得Bundle时,这也有效。

答案 5 :(得分:3)

为类的dynamicType加载xib

    let bundle = NSBundle(forClass: self.dynamicType)
    let nib = UINib(nibName: "CellForAlert", bundle: bundle)
    let view =  nib.instantiateWithOwner(self, options: nil).first as! UIView
    view.frame = bounds
    view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
    self.addSubview(view);

答案 6 :(得分:2)

如果您正在上课,那么

Bundle(for: type(of: self))

有时候您可能会在结构中工作,那么您需要使用捆绑软件中的任何类

Bundle(for: AnyClassInTheBundle.self)

答案 7 :(得分:1)

雨燕5

Bundle(for: Self.self)

答案 8 :(得分:0)

我认为您正在寻找

Bundle.main

Docs

答案 9 :(得分:-1)

在Swift 3.0中,您可以使用:

func kZWGetBundle() -> Bundle{
    return Bundle(for: AnyClass.self as! AnyClass)
}
相关问题