Walid Baba-Moussa Walid Baba-Moussa - 10 months ago 55
iOS Question

Populate a UItableView with new sections when button tapped

I'm working on a project where I've created a TableView in a ViewController 1.
In this VC1 I have also created button (let's call it popupButton) that displays a popupView.
The popupview contains some data, i.e. meals represented by buttons. When the button is tapped I collect the meal selected from the popupview and send it back to the VC1 via delegation. I managed to make this work and I can display the meals selected on the UITableView. The problem is I want to populate the tableView depending on the client selected (In VC1 I have UIbuttons representing each client) as following :

  • Client 1

    • meal A

    • meal B

  • Client 2

    • meal C

    • meal X, etc.

If the button Client 1 is selected and the meal A is tapped create the section C1 as header and meal A meal B and so on. Then when I tap on Client 2 and i select other meals add these meals to a new section whose header will be Client 2. Currently I get Client 1 as the title if it's selected. But if i tap on client 2 and select a new meal it will change the header to Client 2 and won't create a new section. In addition my code works i.e. I can add meals to my table even if no client have been selected at all (it's good so far but I would like it to only work when a client is selected)

In the following code I show only the parts that help understand what I did so far . Any idea that would be really appreciated since I've been looking for a while now. I'm thinking about using struct but i don't have any clue about how to mix it with my case. All the examples that I saw seemed to be about static cases while i'm looking for something dynamic. Thank to you dear reader for taking the time to read my problem and helping a ''desperate soul''.

var meal: String? // this var is used to collect the name of the meal

var mycustomer:String = "" // this var gets the name of the customer
@IBAction func clientselected(sender: UIButton) {
if sender.selected {
sender.backgroundColor = UIColor.lightGrayColor()
sender.selected = false

print ("the button is unselected")

else {
sender.backgroundColor = UIColor.redColor()
sender.selected = true
print ("the button is selected")
let clientname = sender.titleLabel!.text
mycustomer = clientname!


var myarray = [String]() // Create an empty array of strings that we can fill later on with the meals selected

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return myarray.count // Gets the number of strings in the array

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCellWithIdentifier("Leschoix", forIndexPath:indexPath) as UITableViewCell!
cell.textLabel?.text = myarray[indexPath.row]
return cell


func tableView(tableView: UITableView, titleForHeaderInSection section: Int)-> String?
return "\(mycustomer)"}

func foodselected(valuesent:String) { // this func gets the name of the meal tapped in the popUpView through delegation
let meal = valuesent
myarray.append(meal) // each meal selected will be added up to the empty myarray
print ("Here is the food array \(myarray)")


Answer Source

I try to answer you as far as I understood what you need.

So we want to be able to have more than one section. So we need a variable to make it possible to change the number of sections in the tableView.

var numberOfSections: Int = 1

func numberOfSectionsInTableView(tableView: UITableView) -> Int {

     return numberOfSections

That way we can change numberOfSections depending on our needs to have 1 or 2 sections in our TableView.

Then we need to have more than one Array to define the numberOfRowsInSection. Otherwise we will have the exact same elements per section. If we use your current version. Both sections would have the exact same content.

var sectionOneArray = [String]()
var sectionTwoArray = [String]()

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

if section == 0 {
     return sectionOneArray.count

if section == 1 {
     return sectionTwoArray.count

     return 0 

We'll also need two customer Strings to fill the titleForHeaderInSection.

var myFirstCustomer = ""
var mySecondCustomer = ""

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

        if section == 0 {
            return myFirstCustomer

        if section == 1 {
            return mySecondCustomer

Now we can populate the arrays and tell our App if we want one or two sections depending on the amount of customers like that. We also need to have a possibility to tell if we choose the Menus in the Popup for Customer 1 or Customer 2, but I currently have no idea what your Popup looks like, but the code would be something like that:

func foodselected(valuesent:String) { 

     if popUpChoseForCustomerOne {
          let meal = valuesent


     if popUpChoseForCustomerTwo {
          let meal = valuesent

          numberOfSections = 2 



I did this code without IDE, so it might not be perfect. But it should definitely give you the idea of how I would handle the issue.