Swift 等效于[ NSBundlebundleForClass: [ self class ]]

什么是快速等效的下一代码:

[NSBundle bundleForClass:[self class]]

我需要来自测试包(JSON 数据)的加载资源

38371 次浏览

从没用过,但我觉得应该是这样:

Swift < = 2. x

NSBundle(forClass: self.dynamicType)

斯威夫特3. x

Bundle(for: type(of: self))
let bundle = NSBundle(forClass:object_getClass(self))

我个人喜欢:

let bun = NSBundle(forClass: self.classForCoder)

为类的 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);

斯威夫特3:

Bundle(for: type(of: self))

在 Swift 3.0中,你可以使用:

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

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

Bundle(for: self.classForCoder)

当您想要在测试目标中获得 Bundle时,这也是可行的。

如果你在上课

Bundle(for: type(of: self))

有时您可能在一个结构中工作,然后您需要使用捆绑包中的任何类

Bundle(for: AnyClassInTheBundle.self)

Swift 5

Bundle(for: Self.self)