0

I have a TableViewController embedded within a NavigationController. The app is working fine at this point. But now I want to add a TextField above the TableView:

Want a TextField added above the TableView

But I can't seem to be able to drag a TextField from the Object Library above the TableView. It drops it onto the Navigation Item but that isn't what I want. I tried adding a new ViewController, add a TextField to it, and tried dragging the TableView from my existing TableViewController onto it, but that isn't possible. What is the proper approach to redesigning an existing app by taking existing UI elements and embedding them into other views and still retain the existing functionality?

Kaplan
  • 23
  • 6

2 Answers2

0

By dragging the UITextField there, you are trying to add two views to the UITableViewController or UIViewController. A UIViewController (or UITableViewController) only has one view and then that view can have multiple subviews. So that is probably why the drag and drop does not work as you tried it, you were basically trying to add more than one view to the view controller directly as opposed to adding subviews of a UIView.

But you probably would not want to just embed the UITextField as some arbitrary subview of your table view even though that would theoretically be possible. In this case it might be floating around somewhere or appear in the middle of the screen. What you would probably want to do is embed a UITextField into a table view cell (UITableViewCell), so you can enter some text into that table view cell.

There are some tutorials and also other answers on StackOverflow on how to embed a UITextField into a table view cell.

Raphael
  • 243
  • 1
  • 9
0

Rather than trying to mess with the objects in the StoryBoard, I ended up doing this:

  1. Deleted all the objects in the Storyboard. So basically I trashed the TableViewController.

  2. Added a plain ViewController.

  3. Added TextField to the top of the ViewController.

  4. Added TableView to the ViewController below the TextField.

  5. Arranged and added constraints.

  6. Changed the existing ViewController.swift class header:

     class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
    
  7. Ctrl-dragged an IBOutlet from the TableView:

     @IBOutlet weak var tblView: UITableView!
    

    So by doing this, I get to keep most of the code in ViewController.swift.

  8. Set delegate and datasource:

     tblView.delegate = self
     tblView.dataSource = self
     textField.delegate = self
    
  9. Methods for complying with the TableViewDelegate protocol now lose the override specifier, example:

     func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         return 1
     }
    
Kaplan
  • 23
  • 6