Невозможно правильно заполнить данные массива в представлении коллекции, которое находится внутри табличного представления - PullRequest
0 голосов
/ 01 июня 2018

enter image description here

Подтип напитков (например, Kingfisher, budwiser) показывает в представлении сбора, которое находится внутри представления таблицы. Я использовал заголовок представления таблицы для заполнения данных типов напитков, таких как пиво, домашний скотч, импортированный скотч

Примечание: данные типа напитка, получаемые из данных подтипа json и марки напитка из массива

Я хочу заполнить данные массива tag1 в первом представлении коллекции, а затем данные массива tag2 во второмпредставление коллекции .. как это.

import UIKit
import AlignedCollectionViewFlowLayout
import Alamofire

class DrinkPreferenceViewController: UIViewController,UICollectionViewDelegate,UITableViewDelegate,UITableViewDataSource,UICollectionViewDataSource{


    var twoDimensionalArrayList = [ExpandableDrinks]()

    let tag1 = ["Kingfisher", "Calsberg", "Budwiser", "Bira", "Tuborg", "Corona", "Heineken", "Miller", "Hoegaarden"]
    let tag2 = ["Vat 69", "Black & White"]
    let tag3 = ["Johnny Walker", "Chivas Regal", "Ballentines", "Teachers", "Dewars"]
    let tag4 = ["Blenders Pride", "Signature", "Royal Stag", "Antiquity"]
    let tag5 = ["Jack Daniels", "Jim Beam", "Jamesons", "Monkey Shoulder"]
    let tag6 = ["Glenlivet", "Glenfiddich", "Glenmorangie", "Singleton"]
    let tag7 = ["Absolute", "GreyGoose", "Smirnoff", "Ketalone"]
    let tag8 = ["Old Monk", "Bacardi", "Captain Morgan", "Malibu\n"]
    let tag9 = ["Don Julio", "Sauza", "Patron", "Calle 23", "Ocho", "Tapatio", "Cabeza", "Jose Cuervo", "Herradura"]
    let tag10 = ["Sula", "Fratelli Gran Cuvee", "Reveilo", "Sangria", "La \' Reserve", "Rasa Shiraz"]
    let tag11 = ["Jaggerbomb", "Absinthe\n", "B -52", "White Gummy Bear", "Buttery Nipple", "Afterburner", "Kamikaze"]
    //let tags3 = ["Kingfisher", "Calsberg"]
    var dataSource: [[String]] = [[]]

    var drinkTypeNameArray = [String]()
    var subDrinkNameArray = [[String]]()

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

         dataSource = [tag1,tag2,tag3,tag4,tag5,tag6,tag7,tag8,tag9,tag10,tag11]

        // Do any additional setup after loading the view.


        getDrinkDataFromJSON()
    }
    func getDrinkDataFromJSON(){

        let urlString = "http://rednwhite.co.in/webservices/drinks.php"


        do{



            Alamofire.request(urlString, method: .get).responseJSON{

                (response) in

                print(" response :\(String(describing: response.request))")

                guard response.result.isSuccess  else {

                    print("Block 1 ")
                    print(" response :\(response)")

                    print("Error with response: \(String(describing: response.result.error))")

                    return

                }

                guard let dict = response.result.value as? Dictionary <String,AnyObject> else {

                    print(" response :\(response)")

                    print("Error with dictionary: \(String(describing: response.result.error))")

                    return

                }



                guard let dictData = dict["message"] as? [Dictionary <String,AnyObject>] else {
                    print("test 3")
                    print("Error with dictionary data: \(String(describing: response.result.error))")
                    return
                }
                print(" dict data\(dictData)")

                self.drinkTypeNameArray.removeAll()
                self.twoDimensionalArrayList.removeAll()

                for data in dictData{

                    //print("Drink type Data :\(String(describing: data["drink_name"]!))")
                    self.drinkTypeNameArray.append(data["drink_name"]! as! String)
                    //print("array count 5 : \(self.drinkTypeNameArray.count)")

                    self.twoDimensionalArrayList.append(ExpandableDrinks(isExpandable: false, names: ["11"]))
                    //print("two dimensional array count \(self.twoDimensionalArrayList.count)")
                    //print("two dimensional array data \(self.twoDimensionalArrayList)")

                     //print("Drink type Data :\(String(describing: data["sub_drink"]!))")
                    //Populating sub drink name on collection view cell
                    guard let dictSubDrink = data["sub_drink"] as? [Dictionary <String,AnyObject>] else {
                        print("test 3")
                        print("Error with dictionary data: \(String(describing: response.result.error))")
                        return
                    }
                    //print(" sub drink data\(dictSubDrink)")


                    self.subDrinkNameArray.removeAll()
                    for subDrink in dictSubDrink{


                        self.subDrinkNameArray.append([subDrink["sub_drink_name"]! as! String])

                    }

                    print(" sub drink Array\(self.subDrinkNameArray)")
                   // print("drink name array \(self.drinkTypeNameArray)")

                    //self.dataSource.append(self.subDrinkNameArray)

                }

                //print("DataSource :\(self.dataSource)")
                self.tableView.reloadData()

            }


        }catch{

            print("error")
        }

    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let headerView: UIView = UIView.init(frame: CGRect(x: 1, y: 50, width: 276, height: 50))

        headerView.backgroundColor = .clear
        let drinkLabelView: UILabel = UILabel.init(frame: CGRect(x: 60, y: 5, width: 276, height: 24))
        drinkLabelView.text = drinkTypeNameArray[section]

        drinkLabelView.backgroundColor = .clear
        drinkLabelView.textColor = .white
        drinkLabelView.font = UIFont.boldSystemFont(ofSize: 18)
        let checkBoxButtonTapped: UIButton = UIButton.init(frame: CGRect(x: 12, y: 5, width: 24, height: 24))

        if let inSelectedImage = UIImage(named: "checkbox.unselected") {
            checkBoxButtonTapped.setImage(inSelectedImage, for: .normal)
        }

        checkBoxButtonTapped.addTarget(self, action: #selector(handleExpandClosed), for: .touchUpInside)
        checkBoxButtonTapped.tag = section
        let splitterImageView: UIImageView = UIImageView.init(frame:CGRect(x: 4, y: 40, width:400, height:2))
        splitterImageView.image = UIImage(named:"splitter")
        headerView.addSubview(splitterImageView)
        headerView.addSubview(checkBoxButtonTapped)
        headerView.addSubview(drinkLabelView)
        return headerView
    }
    @objc func handleExpandClosed(checkBoxButtonTapped:UIButton){


        print("Trying to close and expand and close section ")

        print(checkBoxButtonTapped.tag)

        let  section = checkBoxButtonTapped.tag
        var indexPaths = [IndexPath]()
        print(" selected section: \(section) selected row:  \(tableView.numberOfRows(inSection: section))")

        for row in twoDimensionalArrayList[section].names.indices{
            print(0,row)
            let indexPath = IndexPath(row:row,section:section)
            indexPaths.append(indexPath)

        }

        let isExpanded = twoDimensionalArrayList[section].isExpandable

        print("is expanded: \(isExpanded)")
        twoDimensionalArrayList[section].isExpandable = !isExpanded



        let selectedImage = UIImage(named: "checkbox.selected")
        let unSelectedImage = UIImage(named: "checkbox.unselected")

        checkBoxButtonTapped.setImage(isExpanded ?  unSelectedImage : selectedImage , for: .normal)


        if isExpanded {
                tableView.deleteRows(at:indexPaths , with: .fade)

            }else{

                tableView.insertRows(at: indexPaths, with: .fade)
            }

    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }



    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

      return 170
   }


    func numberOfSections(in tableView: UITableView) -> Int {

      return drinkTypeNameArray.count

    }


    // MARK: - tableview delegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


            if !twoDimensionalArrayList[section].isExpandable{

                   return 0
               }
               return twoDimensionalArrayList[section].names.count
        }


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



        let cell = tableView.dequeueReusableCell(withIdentifier: "DrinkPreferenceTableViewCell") as! DrinkPreferenceTableViewCell

        return cell
    }

//MARK: - collectionview delegate


    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return dataSource[section].count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {




        let cell = collectionView.dequeueReusableCell(withReuseIdentifier:"DrinkPreferneceCollectionViewCell", for: indexPath) as! DrinkPreferneceCollectionViewCell

         cell.collectionViewDrinkButtonOutlet.setTitle(dataSource[indexPath.section][indexPath.item], for: .normal)
        //cell.collectionViewDrinkButtonOutlet.setTitle(subDrinkNameArray[indexPath.section], for: .normal)

        print("print sub drink array \(dataSource)")

        cell.collectionViewDrinkButtonOutlet.tag
        cell.collectionViewDrinkButtonOutlet.addTarget(self, action:#selector(drinkButtonTapped), for: .touchUpInside)

        return cell
}

    @objc func drinkButtonTapped(collectionViewDrinkButtonOutlet:UIButton){

        collectionViewDrinkButtonOutlet.backgroundColor = UIColor(red: 31/255, green: 17/255, blue:91/255, alpha: 1.0)
        collectionViewDrinkButtonOutlet.layer.borderWidth = 2
        collectionViewDrinkButtonOutlet.layer.borderColor = UIColor(red: 48/255, green: 23/255, blue: 215/255, alpha: 1.0).cgColor

        print("Button Tapped")


    }

}
...