字符串轉(zhuǎn)類:通用AnyClass版在文末
在OC中哥捕,利用
NSClassFromString("XXXTableViewCell")
就可以輕松得到一個類實(shí)例优炬。
在Swift中官扣,如果直接使用這個方法卻會得到nil
祝蝠。
想要達(dá)到的實(shí)現(xiàn):在使用純Model搭建組件的時候,程序在底層框架構(gòu)建Cell的時候只需要一個類名(String類型)就可以完成所有事情绣张,而不需要把cell先初始化出來。
-
字符串轉(zhuǎn)類
/// 字符串轉(zhuǎn)類type
func cellClassFromString(_ className:String) -> AnyClass {
// 1关带、獲swift中的命名空間名
var name = Bundle.main.object(forInfoDictionaryKey: "CFBundleExecutable") as? String
// 2侥涵、如果包名中有'-'橫線這樣的字符,在拿到包名后宋雏,還需要把包名的'-'轉(zhuǎn)換成'_'下橫線
name = name?.replacingOccurrences(of: "-", with: "_")
// 3芜飘、拼接命名空間和類名,”包名.類名“
let fullClassName = name! + "." + className
// 4磨总、因為NSClassFromString()返回的AnyClass?嗦明,需要給個默認(rèn)值返回!
let classType: AnyClass = NSClassFromString(fullClassName) ?? VEBTableViewCell.self
// 類type
return classType
}
在用cellClassFromString(_ className:String)
得到類Type之后,既能使用classType.self
或者 classType.ClassForCorde()
來進(jìn)行重用Cell的注冊蚪燕。
// 注冊cell方法
tableView.register(cellClassFromString("類名").self, forCellReuseIdentifier: "\("類名")!)")
又能直接使用類Type來進(jìn)行tableViewCell的初始化
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// 得到AnyClass
let anyClass: AnyClass = cellClassFromString(str)
// 強(qiáng)轉(zhuǎn)自己需要的類娶牌,使用類方法 .cell來得到一個實(shí)例對象
let classType = anyClass as! VEBTableViewCell.Type
let cell = classType.cell(tableView)
return cell
}
-
(通用)最后也可以把這個方法封裝到String+里面,作為通用方法:
/// 字符串轉(zhuǎn)類
func classFromString(_ className:String) -> AnyClass? {
// 1馆纳、獲swift中的命名空間名
var name = Bundle.main.object(forInfoDictionaryKey: "CFBundleExecutable") as? String
// 2诗良、如果包名中有'-'橫線這樣的字符,在拿到包名后鲁驶,還需要把包名的'-'轉(zhuǎn)換成'_'下橫線
name = name?.replacingOccurrences(of: "-", with: "_")
// 3鉴裹、拼接命名空間和類名,”包名.類名“
let fullClassName = name! + "." + className
// 通過NSClassFromString獲取到最終的類
let anyClass: AnyClass? = NSClassFromString(fullClassName)
// 本類type
return anyClass
}