Ios 使用类名初始化。键入Swift
在UIKit中,如果以编程方式使用UITableView,则需要注册UITableViewCell或CustomCell。 像Ios 使用类名初始化。键入Swift,ios,swift,uitableview,Ios,Swift,Uitableview,在UIKit中,如果以编程方式使用UITableView,则需要注册UITableViewCell或CustomCell。 像 tableViewInstance.register(UITableViewCell.self, forCellReuseIdentifier: "blah blah"); // OR if we want to use our Custom Cell tableViewInstance.register(CustomCell.self, forCellReuseIde
tableViewInstance.register(UITableViewCell.self, forCellReuseIdentifier: "blah blah");
// OR if we want to use our Custom Cell
tableViewInstance.register(CustomCell.self, forCellReuseIdentifier : "blah blah");
问题是,Apple Guys的UITableView如何知道我们提供了什么类型的单元格进行注册,以及它如何通过我们提供的类型在内部初始化单元格。
据我所知,UIKit仍然是用Objective-C编写的,但是 即使在Swift中,您也可以从类类型创建实例, 如以下简化示例所示:
class MyTableView {
var registrations: [String: UITableViewCell.Type] = [:]
func register(theClass: UITableViewCell.Type, forCellReuseIdentifier identifier: String) {
registrations[identifier] = theClass
}
func dequeueCell(withIdentifier identifier: String) -> UITableViewCell {
guard let theClass = registrations[identifier] else {
fatalError("No class has been registered for \(identifier)")
}
return theClass.init(style: .default, reuseIdentifier: identifier)
}
}
这里的类
具有类型UITableViewCell.type
,您可以
可以通过调用
init(style: UITableViewCellStyle, reuseIdentifier: String?)
方法。对于从“元类型值”初始化
init
方法必须显式引用,因此
return theClass(style: .default, reuseIdentifier: identifier)
无法编译。
CustomCell。self
是该类型。实际问题是什么?实际问题是如何使用CustomCell.self
初始化CustomCell()@马丁纳