在Swift中使用 NSClassFromString
xxxixxxx

在Swift中使用 NSClassFromString

需要 工程名 + . + string

1
NSClassFromString(Bundle.main.object(forInfoDictionaryKey: "CFBundleName")! + "." + "CustomCell")

每次写这些很麻烦,所以简单封装下

1
2
3
4
5
6
7
8
9
10
11
12
public func GetClassFromString(_ classString: String) -> AnyClass? {

guard let bundleName: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String else {
return nil
}

var anyClass: AnyClass? = NSClassFromString(bundleName + "." + classString)
if (anyClass == nil) {
anyClass = NSClassFromString(classString)
}
return anyClass
}

以后就可以直接调用

1
GetClassFromString("cellName")
  • Post title:在Swift中使用 NSClassFromString
  • Post author:xxxixxxx
  • Create time:2020-11-02 00:00:00
  • Post link:https://xxxixxx.github.io/2020/11/02/100-在Swift中使用-NSClassFromString/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.
 Comments