Best way to tell the UITableView which data should be display in Swift

I'm new to Swift and I followed some tutorials. They are showing how you are suppose to use a UITableView by using a UITableViewController. The data displayed in the UITableView are stored in an Array inside the UITableViewController. I'm OK with it.

Based on this, I tried to make a UITableView with two arrays :

struct Spending {
    var title: String
    var amount: Float
    var date: Date?
 }

class TableViewControllerSpending: UITableViewController, SpendingProtocol {
        var spendingsTemporary : [Spending] = [Spending(title: "Shoes", amount: 245.99, date: Date())]
        var spendingsPermanent : [Spending] = [Spending(title: "Taxes", amount: 125.50, date: Date())]
}

I would like to use 2 arrays to display both of them depending on the navigation. For instance, when you click on a button "My permanent spending" the UITableView only shows the 'permanent' array data or if you click on "All my spending" you can see the content of the 2 arrays.

What is the best solution to do tell the UITableView which data should be display ?

Thank you.

Upvotes: 0

Views: 92

Answers (2)

rmaddy
rmaddy

Reputation: 318784

Based on your comment, the best solution is to make TableViewControllerSpending a generic view controller that can render a provided array of Spending objects.

class TableViewControllerSpending: UITableViewController, SpendingProtocol {
    var spendings = [Spending]()
}

Implement all of the normal table view methods based on the spendings array.

In some appropriate prepareSegue method called from the two buttons, you get access to the TableViewControllerSpending as the destination controller and then based on the button that was tapped, you set the spendings property with one of the two main lists of Spendings that you have.

With this approach your TableViewControllerSpending has no knowledge that there are two separate lists of data. It just knows how to show a list.

Upvotes: 0

Shehata Gamal
Shehata Gamal

Reputation: 100503

You can try

var isPermanent  = true

//

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

    return  isPermanent ? spendingsPermanent.count : spendingsTemporary.count 

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = areaSettTable.dequeueReusableCell(withIdentifier:CellIdentifier1) as! notifyTableViewCell

   if isPermanent {

  }
  else {

  }

    return cell
}

//

Change isPermanent according to the clicked button and then

tableView.reloadData()

Note you can create one array and assign it the current array and deal with only one array

Upvotes: 2

Related Questions