IOS 反射按网上的操作不成功,怎么办?

  1. ViewController里的代码 :

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let anyobjectype : AnyObject.Type = (NSClassFromString("testReflect.ABC"))!
    // testReflect为项目的name, ABC为要加载的UIVIEW类的类名
    let nsobjectype : NSObject.Type = anyobjectype as! NSObject.Type
    let rec: AnyObject = nsobjectype
    let currentView: UIView = rec as! UIView
    
    self.view.addSubview(currentView)
}}
  1. uiview 里的代码
    class ABC: UIView {

    override init(frame: CGRect) {

    super.init(frame: frame)
    //把背景色设为透明
    print("you got it override init")
    self.backgroundColor = UIColor.green

    }

    required init?(coder aDecoder: NSCoder) {

    fatalError("init(coder:) has not been implemented")
    

    }
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {

    print("you got it draw")
    //self.backgroundColor = UIColor.brown

    }

}

### 想通过一个uiview的类名的字符串(这里为"ABC"),来加载这个类?我用的反射,但没有成功,请问怎么改呢?

阅读 1.9k
1 个回答

//  nsobjectype 是一个 Class    
let nsobjectype : NSObject.Type = anyobjectype as! NSObject.Type
//  rec 是一个 Class
let rec: AnyObject = nsobjectype
//  currentView 是一个 Class 
let currentView: UIView = rec as! UIView
//  currentView 应该是一个 object,
//  建议: let currentView: UIView = rec() as! UIView
//  需要把 currentView 实例化


//    self.view 直接 add 就崩溃了
self.view.addSubview(currentView)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进