swift不建议用反射,那用什么来解决通过类名获取类呢?

SWIFT不建议用反射来操作,但我怎么来处理一个string的列表,点击列表中的一个cell时,通过这个string得到对应的类,并加入对应的类的UIVIEW呢?

阅读 3.6k
1 个回答

不知道你具体的需求是怎么样的。
如果是烦恼TableView注册或者获取Cell的话。


extension UITableView {
    func registerNib(withCellClass clz: Swift.AnyClass, bundle: Bundle? = nil) {
        let className = String(describing: clz)
        let nib = UINib(nibName: className, bundle: bundle)
        self.register(nib, forCellReuseIdentifier: className)
    }

    func dequeueReusableCell<T: UITableViewCell>(type: T.Type, for indexPath: IndexPath) -> T? {
        let className = String(describing: T.classForCoder())
        guard let cell = self.dequeueReusableCell(withIdentifier: className, for: indexPath) as? T else {
            fatalError("cell of [\(className)] is not register as \(className)")
        }
        return cell
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题