I create two view. 1. ViewController by storyboard 2. A UIView by new a class. I want to use UIView class name: "ViewOne" to convert to a class, then load this UIView into the ViewController.
viewcontroller code:
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 code:
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
}
result: Could not cast value of type 'TestIOSReflect.ViewOne' (0x109bc9570) to 'UIView' (0x10c2cdab0).
I retest after below suggestion: in ViewOne class: add " @objc(ViewOne) " in viewcontroller class: removed all below code:
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)
Replaced by below code:
if let viewOneClass = NSClassFromString("ViewOne") as? NSObject.Type{
let ViewOne = viewOneClass.init()
//self.view.addSubview(ViewOne)// doesn't work }
After run the project: in ViewOne class, printed out "It's ViewOne" ,but didn't run the code self.backgroundColor = UIColor.yellow
You can specify name for the symbol in Objective-C which omits the namespace in objective C by using the @objc annotation:
Then try to check if that class exists with the following code: