简体   繁体   中英

Use Swift nested class as UIViewController in storyboard

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:

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 {
      ...
   }
}

That way I could use them by doing Settings.Controller and Settings.Model which I think would look pretty nice.

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:

  1. Nested classes are references by using the dot notation: Settings.Controller but Interface Builder does not see that as a valid class name

The solution was simple, give the controller it's own Objc name:

class Settings {
   @objc(SettingsController)
   class Controller: UIViewController {
   }
   ...
}

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 .

I don't think storyboards supports that (yet), so in the meantime you need to use some workarounds.

If all you want is the syntax Settings.Controller , you can do this: (Inspired by this answer )

Declare your Settings.Controller class not as a nested class, but as a standalone class SettingsController :

class SettingsController : UIViewController { ... }

Then in Settings , add a typealias :

class Settings {
    typelias Controller = SettingsController
    class Model { ... }
}

Now you can use SettingsController in the storyboard, but Settings.Controller in code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM