ios - 从字符串数组中获取 NSClassFromString - Swift

标签 ios class uiviewcontroller swift

我正在尝试编写一个函数,从我的字符串数组中加载一个特定的 View Controller >。然而,我很快就在这个概念上苦苦挣扎——我在 Objective - C 中实现了这一点。

static NSString const *const viewControllerClassName[3] = {@"one", @"two", @"three"};

.

// get the name of the class of the viewcontroller that will be shown on this page
const NSString *className = viewControllerClassName[1];
Class class = NSClassFromString((NSString *)className);

UIViewController *controller = [[class alloc] initWithContainer:self];

我如何在 Swift 中实现这个概念?由于 Class 在 Swift 中没有特色?

最佳答案

对于 NSObject 派生类(例如对于 View Controller 类),NSClassFromString() 在 Swift 中仍然有效 (另请参阅 Swift language NSClassFromString 的各种答案)。

我在 type 上添加了一个条件转换 确保创建的类确实是 UIViewController 的子类。 因此,编译器“知道”可用的 init 方法,并且 创建的实例是 UIViewController

let viewControllerClassName = [ "one", "two", "three"]

let className = viewControllerClassName[1]
if let theClass = NSClassFromString(className) as? UIViewController.Type {
    let controller = theClass(nibName: nil, bundle: nil)
    // ...
}

Swift 3 的更新:

if let theClass = NSClassFromString(className) as? UIViewController.Type {
    let controller = theClass.init(nibName: nil, bundle: nil)
    // ...
}

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

相关文章:

iphone - UITextField resignFirstResponder 不工作?

ios - iOS 10 中的 UITableView 标题 View 重叠单元格

c++ - 来自大括号初始化列表的短 C++ 类构造函数

reactjs - 使用函数动态添加 html 类?

ios - 重定向到另一个 View Controller

跨安装的 ios 唯一标识符

ios - SpriteKit 中的坠落物体?

class - 在UML类图中,如果B被类A使用的接口(interface)使用,我是否应该绘制从类A到B的依赖关系?

ios - 为什么 TabBar 在 segue 之后隐藏?

ios - 如何在 UICollectionViewSectionHeader 中嵌入 UICollectionView