在OC里面我们可以很简单的通过类名创建一个实例,swift里面我们怎么办呢
OC代码如下:
Class className = NSClassFromString(displayClassName); UIViewController *view = [[className alloc]init];
swift2.0 有了很大的改变,这里不是我们讨论的重点,swift里面我们不能简单的使用NSClassFromString方法了
方法一:
swift提供了@objc()方法,只要在我们的想要创建的类里面实现这个方法就行了,比如这样:
// // WaterGlassAnimationViewController.swift // TestDemoPark // // Created by ss on 15/10/9. // Copyright © 2015年 Yasin. All rights reserved. // import UIKit @objc(WaterGlassAnimationViewController) class WaterGlassAnimationViewController: UIViewController {然后我们在使用的时候就可以直接使用NSClassFromString了
let classNameStr = "WaterGlassAnimationViewController" if let className = NSClassFromString(classNameStr) { if let viewClass = className as? UIViewController.Type { let view = viewClass.init() view.title = titleArr[indexPath.row] self.navigationController?.pushViewController(view,animated: true) } }但是这样我们需要在类上面实现方法,有时候也不是很方便
方法二:
let classNameStr = <span><span class="string">"WaterGlassAnimationViewController"</span><span></span></span> if let view = swiftClassFromString(classNameStr) { view.title = titleArr[indexPath.row] self.navigationController?.pushViewController(view,animated: true) }我们需要写一个swiftClassFromString自定义方法
func swiftClassFromString(className: String) -> UIViewController? { //方法 NSClassFromString 在Swift中已经不起作用了no effect,需要适当更改 //官方文档方法:let myPersonClass: AnyClass? = NSClassFromString("MyGreatApp.Person") if let appName = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as? String { let classStringName = "_TtC\(appName.characters.count)\(appName)\(className.characters.count)\(className)" let cls: AnyClass? = NSClassFromString(classStringName) assert(cls != nil,"class not found,please check className") if let viewClass = cls as? UIViewController.Type { let view = viewClass.init() return view } } return nil; }