代码之家  ›  专栏  ›  技术社区  ›  A.Sheh

我可以通过一个字符串得到一个类

  •  0
  • A.Sheh  · 技术社区  · 6 年前

    我创建了两个视图。1故事板2的ViewController。新类的UIView。我想使用UIView类名:“ViewOne”转换成一个类,然后将这个UIView加载到ViewController中。

    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类中:添加“@objc(ViewOne)” 在viewcontroller类中:删除了以下所有代码:

    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

    1 回复  |  直到 6 年前
        1
  •  1
  •   Vlad Z.    6 年前

    您可以使用 注释:

    @objc(ViewOne)
    class ViewOne: UIView {}
    

    // Variable must first be casted into a specific type
    if let viewOneClass = NSClassFromString("ViewOne") as? NSObject.Type {
      // Initialization
      let viewOne = viewOneClass.init()
      //// Do your stuff
      ....
    }
    
    推荐文章