SWIFT 3 : 在 didSelectItemAt 中从动态字符串设置目标 UIViewController 名称
SWIFT 3 : set target UIViewController name from dynamic string in didSelectItemAt
我有一个包含字符串类型 link 值的结构。字符串是 ViewController 的名称。我想将此值传递给 UICollectionView didSelectItemAt 并将 Hero 转换为相应的 UIViewController .. 但我一直在研究如何使用字符串值来实例化 ViewController 对象。
我的 collectionView 工作正常,结构数据被传递到单元格并显示..只是不知道如何使用带有 didSelectItemAt 的 link 字符串 ...
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print((tableRows[indexPath.row] as! Projects).link) // proves the String is available for use
let vc = (tableRows[indexPath.row] as! Projects).link as UIViewController
vc.isHeroEnabled = true
vc.heroModalAnimationType = .zoom
self.hero_replaceViewController(with: vc)
}
抛出:
Cannot convert value of type 'String' to type 'UIViewController' in coercion
Swift 使用静态类型,而不是动态类型。这不是Objective-C!你不能把一个字符串变成一个视图控制器类型,更不用说变成一个实际的视图控制器实例,就像你试图做的那样。最后,无论如何你都不想说 as UIViewController
,因为普通的 UIViewController 没有 isHeroEnabled
属性。您必须实例化您尝试创建的实际类型的视图控制器,并且该视图控制器的名称不能对编译器隐藏并且只能在运行时使用;它必须出现在您的代码中。
我有一个包含字符串类型 link 值的结构。字符串是 ViewController 的名称。我想将此值传递给 UICollectionView didSelectItemAt 并将 Hero 转换为相应的 UIViewController .. 但我一直在研究如何使用字符串值来实例化 ViewController 对象。
我的 collectionView 工作正常,结构数据被传递到单元格并显示..只是不知道如何使用带有 didSelectItemAt 的 link 字符串 ...
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print((tableRows[indexPath.row] as! Projects).link) // proves the String is available for use
let vc = (tableRows[indexPath.row] as! Projects).link as UIViewController
vc.isHeroEnabled = true
vc.heroModalAnimationType = .zoom
self.hero_replaceViewController(with: vc)
}
抛出:
Cannot convert value of type 'String' to type 'UIViewController' in coercion
Swift 使用静态类型,而不是动态类型。这不是Objective-C!你不能把一个字符串变成一个视图控制器类型,更不用说变成一个实际的视图控制器实例,就像你试图做的那样。最后,无论如何你都不想说 as UIViewController
,因为普通的 UIViewController 没有 isHeroEnabled
属性。您必须实例化您尝试创建的实际类型的视图控制器,并且该视图控制器的名称不能对编译器隐藏并且只能在运行时使用;它必须出现在您的代码中。