使用通用将情节提要链接到UIViewController [英] Link Storyboard to UIViewController with Generic

查看:34
本文介绍了使用通用将情节提要链接到UIViewController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个视图控制器,用于以通用方式显示模型对象的详细信息:

I have this view controller, meant to present model object details in a generic way:

class APIModelDetailsVC<T where T: APIModel>: UIViewController {...}

我希望我的情节提要使用该课程.我可以在Interface Builder中对其进行分配:

I'd like my storyboard to use this class. I'm able to assign it in Interface Builder:

我通过表视图的didSelect方法(包括指定通用占位符的类型)来准备此ViewController:

I do the preparation of this ViewController in a tableview's didSelect method (including specifying the type for the generic placeholder):

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
  print("didSelectRowAtIndexPath \(indexPath.row)")
  if let vc = UIStoryboard(name: "APIModelDetailsVC", bundle: nil).instantiateInitialViewController() as? APIModelDetailsVC<StarWarsPerson> {
    vc.model = data[indexPath.row]
    self.navigationController?.pushViewController(vc, animated: true)
  }
}

当我尝试导航到该视图控制器时,出现以下控制台错误:

When I attempt to navigate to this view controller, I get the following console error:

Unknown class _TtC14api_collection17APIModelDetailsVC in Interface Builder file.

这是故事板的已记录限制吗?有没有一种方法可以/我应该指定泛型,以便情节提要可以链接到它?

Is this a documented limitation with Storyboards? Is there a way I can/should specify the generic so the storyboard can link to it?

推荐答案

Storyboards具有通用类的问题.问题是Interface Builder通过Objective-C运行时与ViewController通信.因此,InterfaceBuilder仅限于Objective-C提供的功能.在这种情况下,不支持泛型.

Storyboards have a problem with having a generic class. The thing is that Interface Builder communicates to the ViewController through the Objective-C runtime. Because of this, InterfaceBuilder is limited to the features that Objective-C provides. In this case, generics are not supported.

一种解决方法是使用NSObject.load()方法.

A workaround for this is using the .load() method of NSObject.

例如,如果您有提到的ViewController类:

For example, if you have the mentioned ViewController class:

class APIModelDetailsVC<T where T: APIModel>: UIViewController {...}

您应该创建一个虚拟" ViewController,例如:

You should create a "dummy" ViewController such as:

class StartWasModelDetailsVC: APIModelDetailsVC<StarWarsPerson> {...}

并在情节提要中设置最后一个ViewController.然后,为了在Objective-c运行时中实现此目的,应在AppDelegate或加载此控制器之前的某处添加以下内容.

and set this last ViewController in the storyboard. Afterwards, in order to make this work in the Objective-c runtime, you should add the following in your AppDelegate or somewhere before this controller is loaded.

StartWasModelDetailsVC.load()

希望有帮助!

这篇关于使用通用将情节提要链接到UIViewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆