Ios 无法在表视图内的集合视图上正确填充数组数据

Ios 无法在表视图内的集合视图上正确填充数组数据,ios,arrays,swift,uicollectionview,tableview,Ios,Arrays,Swift,Uicollectionview,Tableview,饮料品牌子类型(如翠鸟、百威)显示在表视图内的集合视图中。我使用表视图标题填充饮料类型数据,如啤酒、国产苏格兰威士忌、进口苏格兰威士忌 注意:饮料类型数据来自json,饮料品牌子类型数据来自数组 我想在第一个集合视图上填充tag1数组数据,然后在第二个集合视图上填充tag2数组数据..就像这样 import UIKit import AlignedCollectionViewFlowLayout import Alamofire class DrinkPreferenceViewControl

饮料品牌子类型(如翠鸟、百威)显示在表视图内的集合视图中。我使用表视图标题填充饮料类型数据,如啤酒、国产苏格兰威士忌、进口苏格兰威士忌

注意:饮料类型数据来自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")


    }

}
导入UIKit
导入AlignedCollectionViewFlowLayout
进口阿拉莫菲尔
类DrinkPreferenceViewController:UIViewController、UICollectionViewDelegate、UITableViewDelegate、UITableViewDataSource、UICollectionViewDataSource{
var twoDimensionalArrayList=[ExpandableDrinks]()
让tag1=[“翠鸟”、“卡尔斯伯格”、“布德怀瑟”、“比拉”、“图堡”、“科罗纳”、“喜力”、“米勒”、“霍加尔登”]
让tag2=[“Vat 69”,“黑白”]
let tag3=[“约翰尼·沃克”、“芝华士富豪”、“芭蕾舞剧”、“教师”、“杜瓦瓶”]
let tag4=[“搅拌机骄傲”、“签名”、“皇家雄鹿”、“古董”]
let tag5=[“杰克·丹尼尔斯”、“吉姆·比姆”、“詹姆逊”、“猴肩”]
设tag6=[“Glenlivet”、“Glenfiddich”、“Glenmorangie”、“Singleton”]
设tag7=[“绝对”、“灰色”、“斯米尔诺夫”、“氯胺酮”]
让tag8=[“老和尚”、“百加得”、“摩根船长”、“马里布”]
让tag9=[“唐·胡里奥”、“索萨”、“赞助人”、“卡莱23”、“奥乔”、“塔帕蒂奥”、“卡贝扎”、“何塞·库埃沃”、“赫拉杜拉”]
让tag10=[“苏拉”、“弗拉泰利格兰库维”、“雷维洛”、“桑格里亚”、“拉萨保留地”、“拉萨设拉子”]
让tag11=[“Jaggerbomb”,“Absince\n”,“B-52”,“白色粘熊”,“黄油乳头”,“加力”,“神风”]
//让标记3=[“翠鸟”、“卡尔斯伯格”]
变量数据源:[[String]]=[[]]
var drinkTypeNameArray=[String]()
var subdrinkanamerary=[[String]]()
@IBVAR表格视图:UITableView!
重写func viewDidLoad(){
super.viewDidLoad()
数据源=[tag1、tag2、tag3、tag4、tag5、tag6、tag7、tag8、tag9、tag10、tag11]
//加载视图后执行任何其他设置。
getDrinkDataFromJSON()
}
func getDrinkDataFromJSON(){
让URL字符串=”http://rednwhite.co.in/webservices/drinks.php"
做{
请求(urlString,方法:.get).responseJSON{
(答复)在
打印(“响应:\(字符串(描述:response.request)))
guard response.result.isSuccess else{
打印(“块1”)
打印(“响应:\(响应)”)
打印(“响应错误:\(字符串(描述:response.result.Error)))
返回
}
guard let dict=response.result.value as?Dictionary else{
打印(“响应:\(响应)”)
打印(“字典错误:\(字符串(描述:response.result.Error)))
返回
}
guard let dictData=dict[“message”]作为?[Dictionary]其他{
打印(“测试3”)
打印(“字典数据错误:\(字符串(描述:response.result.Error)))
返回
}
打印(“dict数据\(dictData)”)
self.drinkTypeNameArray.removeAll()
self.twoDimensionalArrayList.removeAll()
对于dictData中的数据{
//打印(“饮料类型数据:\(字符串(描述:数据[“饮料名称”!))))
self.drinkTypeNameArray.append(数据[“饮料名称”]!as!字符串)
//打印(“数组计数5:\(self.drinkTypeNameArray.count)”)
self.twoDimensionalArrayList.append(可扩展饮料(isExpandable:false,名称:[“11”]))
//打印(“二维数组计数\(self.twodialarraylist.count)”)
//打印(“二维数组数据\(self.twoDimensionalArrayList)”)
//打印(“饮料类型数据:\(字符串(描述:数据[“sub_饮料”]!)))
//在集合视图单元格中填充子饮料名称
guard let dictSubDrink=数据[“sub_-drink”]为?[Dictionary]其他{
打印(“测试3”)
打印(“字典数据错误:\(字符串(描述:response.result.Error)))
返回
}
//打印(“子饮料数据\(子饮料)”)
self.subdrinnamearray.removeAll()
适用于DictSubdrive中的subDrink{
self.subdrinkanamearray.append([subDrink[“sub_-drink\u-name”]!as!String])
}
打印(“子饮料数组\(self.subDrinkNameArray)”)
//打印(“饮料名称数组\(self.drinkTypeNameArray)”)
//self.dataSource.append(self.subDrinkNameArray)
}
//打印(“数据源:\(self.DataSource)”)
self.tableView.reloadData()
}
}抓住{
打印(“错误”)
}
}
func tableView(tableView:UITableView,viewForHeaderInSection:Int)->UIView{
让headerView:UIView=UIView.init(帧:CGRect(x:1,y:50,宽度:276,高度:50))
headerView.backgroundColor=.clear
let-drinkLabelView:UILabel=UILabel.init(帧:CGRect(x:60,y:5,宽度:276,高度:24))
drinkLabelView.text=drinkTypeNameArray[节]
drinkLabelView.backgroundColor=.clear
drinkLabelView.textColor=.white
drinkLabelView.font=UIFont.boldSystemFont(字体大小:18)
让checkBoxButtonTapped:UIButton=UIButton.init(帧:CGRect(x:12,y:5,宽度:24,高度:24))
如果let inSelectedImage=UIImage(名为:“checkbox.unselected”){
checkBoxButtonTapped.setImage(插入选定图像,用于:。正常)