我创建了两个视图。1. 故事板的 ViewController 2. 新类的 UIView。我想使用 UIView 类名:“ViewOne”来转换为一个类,然后将此 UIView 加载到 ViewController 中。
视图控制器代码:
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.blue
let anyobjectype : AnyObject.Type = (NSClassFromString("TestIOSReflect.ViewOne"))!
// TestIOSReflect is project name, ViewOne is the UIVIEW name
let nsobjectype : NSObject.Type = anyobjectype as! NSObject.Type
let rec: AnyObject = nsobjectype
let currentView: UIView = rec as! UIView
self.view.addSubview(currentView)
}
UIView:ViewOne 代码:
override init(frame: CGRect) {
super.init(frame: frame)
print("It's ViewOne")
self.backgroundColor = UIColor.yellow
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
print("It's draw func of ViewOne")
//self.backgroundColor = UIColor.brown
}
结果:无法将“TestIOSReflect.ViewOne”(0x109bc9570)类型的值转换为“UIView”(0x10c2cdab0)。
我在以下建议后重新测试:在 ViewOne 类中:在 viewcontroller 类中添加“@objc(ViewOne)”:删除以下所有代码:
self.view.backgroundColor = UIColor.blue
let anyobjectype : AnyObject.Type = (NSClassFromString("TestIOSReflect.ViewOne"))!
// TestIOSReflect is project name, ViewOne is the UIVIEW name
let nsobjectype : NSObject.Type = anyobjectype as! NSObject.Type
let rec: AnyObject = nsobjectype
let currentView: UIView = rec as! UIView
self.view.addSubview(currentView)
替换为以下代码:
if let viewOneClass = NSClassFromString("ViewOne") as? NSObject.Type{
let ViewOne = viewOneClass.init()
//self.view.addSubview(ViewOne)// doesn't work }
运行项目后:在 ViewOne 类中,打印出 "It's ViewOne" ,但没有运行代码 self.backgroundColor = UIColor.yellow