Search code examples
iosxcodeuiviewuiviewcontrollerxcode-storyboard

Xcode Storyboard: Can't add View to ViewController


I'm using Xcode 10 (with Swift 5 and for iOS 12) and my app is currently set up like this:

  1. UIViewController 1 (login screen) - segue12 to ->
  2. NavigationController that automatically created
  3. UIViewController 2 with a UITableView - segue23 to ->
  4. UIViewController 3 (detailed info about an item in the UITableView with automatically created "back" button)

enter image description here

The NavigationBar only contains a " ".

I now want to add another UIView with a button below the UITableView but Xcode won't let me drag it below the UITableView, only either into the UITableView or directly underneath "First Responder", which puts the View outside into its own window.

If I delete "My Table View", it won't let me drag in a replacement either.

How do I fix this, so I can add the new UIView + UIButton?


Solution

  • NavigationController that automatically created UIViewController 2

    That explains everything. When you drag a navigation controller into the storyboard, what you get is a navigation controller and its root view controller, and the root view controller is a UITableViewController.

    Let's step back for a moment. A view controller can and must have exactly one main view. It occupies the whole scene. It cannot be resized. It cannot have a sibling view, because it has no superview for a sibling view to be a child of. It can only have children (subviews).

    Well, in this case, ViewController2 is a UITableViewController, and MyTableView is ViewController2’s main view. (A table view controller is always configured this way, and that is what you got when you dragged the navigation controller into the storyboard.) That is why you cannot add more views to it, except as subviews, e.g. prototype cell contents. Your button has no place to go except inside the table view.

    So, what to do?

    • If the extra interface you want to add is just a button, the usual solution is to put it into the navigation bar. It becomes part of the table view controller's navigation item.

    • If you don't want to do that — that is, if you really want the button and the table view to be siblings of one another in the interface — then you need to replace ViewController2 itself with an ordinary view controller. Now its main view will be an ordinary view, and you can drag anything you like into it, including a table view and a button. More likely, instead of a bare table view, you would use a container view, with an embed segue to a table view controller.