mardi 5 mai 2015

My fix for my uitableview with sections

I figured it out. whole code below. remember im using alamofire and swiftyjson for simplicity..

Basicly my mechanism is :

1st : get the section name, data and append the section object to sections array. 2nd: while holding that instance of the section object and going thru the menu items array with the json , create the menutiem objects for each menu and use the section object function addItems to add each menuitem to that section. 3rd: check my table functions and see how i call the data of each section...

class MenuViewCell: UITableViewCell {


    @IBOutlet var lbl_nombre : UILabel!
    @IBOutlet var lbl_desc : UILabel!
    @IBOutlet var lbl_precio : UILabel!

}

class VCviendorest: UIViewController, UITableViewDelegate ,UITableViewDataSource, UIWebViewDelegate , UIScrollViewDelegate {

    required init(coder aDecoder: NSCoder) {
        self.DETAILURL = "";
        self.NOMBRERESTAURANT = "";
        self.IDREST = "";
        self.checks = [];

        super.init(coder: aDecoder)
    }


    // Array holders for menu items
    //var items:[MenuItem] = []
    var sections = [Section]()


    class Section  {
        var items: [MenuItem] = []
        var name:String = ""

        func addItem(item: MenuItem) {
            self.items.append(item)
        }

        init(name:String) {
            self.name = name
        }


    }

        class MenuItem : Printable {
            let name:String!
            let desc:String!
            let price:Float!
            var section: Int?

            init(name:String,desc:String,price:Float) {
                self.name = name
                self.desc = desc
                self.price  = price

            }
            var description: String {
                return name
            }
    }



    @IBOutlet weak var navigation: UINavigationItem!

    @IBOutlet var BottomView: UIView!

    @IBOutlet var tableView: UITableView!



    var DETAILURL:String
    var NOMBRERESTAURANT:String
    var IDREST:String
    var checks: [String]

    var originalFrame:CGRect!
    var tabActivated:Bool = true

    // BUTTONS

    @IBOutlet var but_ofertas: UIButton!

    @IBOutlet var but_actividades: UIButton!
    @IBOutlet var but_nube: UIButton!
    @IBOutlet var but_comentarios: UIButton!

    //



    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 50.0

        self.getMenu(self.IDREST)
        self.tableView.dataSource = self
        self.tableView.delegate = self;



        get_checks()



    }




     func numberOfSectionsInTableView(tableView: UITableView)
        -> Int {
           return self.sections.count

    }



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

      return  self.sections[section].items.count


    }

    /* section headers
    appear above each `UITableView` section */
    func tableView(tableView: UITableView,
        titleForHeaderInSection section: Int)
        -> String {
            // do not display empty `Section`s
            if !self.sections[section].items.isEmpty {
                return self.sections[section].name
            }
            return ""
    }

    func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        let header: UITableViewHeaderFooterView = view as UITableViewHeaderFooterView //recast your view as a UITableViewHeaderFooterView
       // header.contentView.backgroundColor = UIColor(red: 0/255, green: 181/255, blue: 229/255, alpha: 1.0) //make the background color light blue

        header.contentView.backgroundColor = UIColor(red: 247.0/255.0, green: 247.0/255.0, blue: 247.0/255.0, alpha: 1.0)
        header.textLabel.textColor = UIColor(red: 234.0/255.0, green: 46.0/255.0, blue: 73.0/255.0, alpha: 1.0) //make the text BAR COLOR
        header.alpha = 1 //make the header transparent
    }


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


      let data = self.sections[indexPath.section].items[indexPath.row]
      let cell : MenuViewCell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as MenuViewCell

        cell.lbl_nombre.text = data.name
        cell.lbl_desc.numberOfLines = 0
        cell.lbl_nombre.numberOfLines = 0
        cell.lbl_desc.text = data.desc
        cell.lbl_precio.text = "RD$\(data.price)" as String
           cell.lbl_nombre.lineBreakMode = NSLineBreakMode.ByWordWrapping
        cell.lbl_desc.lineBreakMode = NSLineBreakMode.ByWordWrapping

        cell.lbl_nombre.sizeToFit()
        cell.lbl_desc.sizeToFit()


        return cell
    }

    // Func getMenu
    func getMenu(id:String) {


        // run in background
        let qualityOfServiceClass = QOS_CLASS_BACKGROUND
        let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
        dispatch_async(backgroundQueue, {
            println("This is run on the background queue")

        Alamofire.request(.GET,"http://ift.tt/1GNUAKF", parameters: ["r": "\(id)"]).responseJSON() {

            (request,response,json,error) in

            if(error != nil) {

                println("there was an \(error)")
            }


            if(json != nil) {

                let jsonObj = JSON(json!);
                let rests = jsonObj as JSON

               // println(jsonObj);

                //generate items


                if let restsarray = rests["menu"].arrayValue as [JSON]? {


                    //var reststo = [RestsModel]()
                   // var arr = [MyItem]()

                    //3
                    for restDict in restsarray {

                        var section_nombre: String? = restDict["tipo"].stringValue
                        var section = Section(name:section_nombre!)
                        self.sections.append(section)
                      //  println("tipo es \(section_nombre)")

                        if let restDictPlatos = restDict["platos"].arrayValue as [JSON]? {

                            for restDict in restDictPlatos {
                            var plato_nombre:String? = restDict["plato_nombre"].stringValue
                            var plato_desc:String? = restDict["desc"].stringValue
                            var plato_price:Float? = restDict["precio"].floatValue

                          //  print("nombre plato: \(plato_nombre)");

                              var plat = MenuItem(name: plato_nombre!, desc: plato_desc!, price: plato_price!)
                                //var section = Section(name:section_nombre!)

                                section.addItem(plat)



                                //for item in self.sections {
                                //self.sections[item.section!].addItem(item)
                                //}

                            }

                    }





                }




            }
               // println("count from self sections is \(self.sections[1].items[1].name)")

            self.tableView.reloadData()
        }





    }

        }) // end run in background

    }
    // End getMenu




}

Aucun commentaire:

Enregistrer un commentaire