ios - 从字符串中获取类并在 Swift 中传递参数

标签 ios swift

我在 objective-c 中有一个方法,它接受字符串并转换为类并将一些公共(public)对象传递给它。

-(UIViewController*)getUIViewController{
 NSString* templateID = @"templateId"; // This value is coming from ba ckend
Class c = NSClassFromString(templateID);
UIViewController* vc = [[c alloc] initWithAppRender:appRenderer];
return vc;
}

现在同样的事情转换为 swift。

func getUIViewController() -> UIViewController? {
    let templateID = "templateId"
    let className = Bundle.main.infoDictionary!["CFBundleName"] as! String + "." + templateID
    let aClass = NSClassFromString(className) as! UIViewController.Type
    return aClass.init()
}

这里的问题是无法传递存在于所有 View Controller 中的公共(public)对象。我想像在 objective-c 中一样传递 apprenderer 对象。

最佳答案

我建议您像这样为所有 ViewController 创建一个基类,

class BaseViewController: UIViewController {

    private var render: NSObject?

    required init(appRenderer: NSObject?) {
        super.init(nibName: nil, bundle: nil)

        self.render = appRenderer
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

然后您可以从服务器返回的类名实例化如下,

func getUIViewController() -> UIViewController? {
    let templateID = "templateId"
    let className = Bundle.main.infoDictionary!["CFBundleName"] as! String + "." + templateID
    let aClass = NSClassFromString(className) as! BaseViewController.Type
    let vc = aClass.init(appRenderer: nil)
    return vc
}

关于ios - 从字符串中获取类并在 Swift 中传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49940201/

相关文章:

ios - 检测 SKNode 上的触摸(快速)

iphone - 验证 iphone 是否已连接到基座

javascript - 如何增加 'react-native-swipeout' 上的按钮宽度以进行 ListView 行滑动(React Native)?

ios - 如何知道 Swift 中哪个 UIView 被点击

ios - 如何在 2 个堆栈 View 之间设置标签的自动布局?

ios - UIWebview全屏尺寸

ios - 当前事件的时间戳/NSDate在UIKit中启动

ios - 首次解锁手机时,如何使 UIDeviceOrientation 自动变为纵向?

ios - 我以编程方式创建了矩形,并在 Storyboard上添加了按钮,按钮被矩形覆盖了。我该如何解决?

swift - [核心数据] :Multiple NSEntityDescriptions claim the NSManagedObject subclass 'Core Data Model' so +entity is unable to disambiguate