在故事板上使用Swift嵌套类作为UIViewController [英] Use Swift nested class as UIViewController in storyboard
问题描述
你们知道在Storyboard中是否可以使用Swift嵌套类作为UIViewController吗?
Do you guys know if it's possible to use a Swift nested class as UIViewController in Storyboard?
我正在研究构建项目的不同方法,其中之一
I'm looking into different ways to structure my projects, one of which is grouping related classes by nesting them in the same main class.
让我用一个例子来解释:
Let me explain with an example:
说我有一个屏幕来显示需要UIViewController和模型的应用程序设置。
我可以创建2个类: SettingsController
和 SettingsModel
,但我想知道是否可以通过将主类 Settings
包含嵌套来使其结构化不是很好吗类 Controller
和 Model
这样的
Say I have a screen for displaying my app's settings which needs a UIViewController and a model.
I could create 2 classes: SettingsController
and SettingsModel
, but I'm wondering if it wouldn't be nice to have it structured otherwise by having a main class Settings
containing nested classes Controller
and Model
like so
class Settings {
class Controller: UIViewController {
...
}
class Model {
...
}
}
这样,我可以通过执行 Settings.Controller来使用它们
和 Settings.Model
,我认为它看起来会很不错。
That way I could use them by doing Settings.Controller
and Settings.Model
which I think would look pretty nice.
现在使用Storyboard时,这种效果很好。在情节提要中,当我选择一个视图控制器来设置自定义类时,如果键入 Setting.Controller
并按Enter,则该字段将无效并被清除。
Now this works fine expect when using storyboard. In Storyboard when I select a view controller to set the custom class, if I type in Setting.Controller
and hit enter, the field does not validate and is cleared.
所以我的问题是,你们知道我在做什么错吗,或者根本不可能吗?
So my question is do you guys know what I'm doing wrong or if this is simply not possible?
推荐答案
当然,是在发布问题后我才找到了解决方案,所以我将其分享给后代。
Of course, it's after having posted the question that I found a solution so I'm sharing it for posterity.
因此,我尝试执行此操作的方式存在一个问题:
So there was 1 problem to the way I was trying to do it:
- 嵌套类是使用点
表示法引用的:Settings.Controller
,但是Interface Builder不会
将其视为有效的类名
- Nested classes are references by using the dot
notation:
Settings.Controller
but Interface Builder does not see that as a valid class name
解决方案很简单,给控制器起自己的Objc名称:
The solution was simple, give the controller it's own Objc name:
class Settings {
@objc(SettingsController)
class Controller: UIViewController {
}
...
}
通过执行此操作,可以为嵌套控制器提供一个ObjC名称,从而将其公开给Interface Builder。现在,您可以通过填写 SettingsController
来引用控制器。
By doing this you give the nested controller an ObjC name thereby exposing it the Interface Builder. Now you can reference the controller by filling in SettingsController
.
这篇关于在故事板上使用Swift嵌套类作为UIViewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!