1

I am making a Grocery list and so far I only have an array with the grocery list items. I want to add " today" at the top, "weekly" after three grocery items and "monthly" before the last three grocery items.

My question is, how would i specify where to insert cells from arrayNum2 which will be " today, weekly and monthly" with the grocery list?

Ex:

  (  Today   )
     item
     item
     item
    Weekly
     item
     item
     item
    Monthly
     item
     item
     item

Here is the code I have

//


import UIKit

class ViewController: UITableViewController{


    var groceries = [Grocery]()




    override func viewDidLoad() {
        super.viewDidLoad()

        self.groceries = [Grocery( name: "Lemon"), Grocery( name: "Bread"), Grocery( name: "Milk"),Grocery( name: "Tomato"),Grocery( name: "Pasta"),Grocery( name: "Soup"),Grocery( name: "Coke"),Grocery( name: "Potato"),Grocery( name: "Chips")]

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.groceries.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
        var grocery : Grocery

        grocery = groceries[indexPath.row]

        cell.textLabel?.text = grocery.name

        return cell
    }

}

and my Grocery.swift

import Foundation

struct Grocery {

    let name: String
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
el txxx
  • 35
  • 3
  • 1
    It sounds like you should use 3 sections in your tableview – Paulw11 Apr 07 '16 at 03:03
  • or in another case if you want in the same section you can use `insertRowsAtIndexPaths(_:withRowAnimation:)`, where you can specify the indexpath to insert the row – HardikDG Apr 07 '16 at 03:07

1 Answers1

0

There are two possible ways to solve this problem

  • Multiple sections: You specify different array in the different sections, so you would have them group and individual in the sections

You have already posted a link of that Sample

  • Insert row at specific locations: You can use insertRowsAtIndexPaths(_:withRowAnimation:) which Inserts rows in the table view at the locations identified by an array of index paths, with an option to animate the insertion.

So from the length of the previous array/ based on your calculation you can insert the row at specific location

Apple Doc: insertRowsAtIndexPaths
insertRowsAtIndexPaths Sample code

Hope it may help someone in future

Community
  • 1
  • 1
HardikDG
  • 5,892
  • 2
  • 26
  • 55