简体   繁体   English

在iOS中,Swift将不同的数组集成到Swift 4中的TableView内部的CollectionView中

[英]In iOS Swift integrate Different array for CollectionView Inside TableView in Swift 4

How to set CollectionView data to Collection tag.collection tag count is not fixed .How to integarte cellForItemAt and numberOfItemsInSection in CollectionView .So I have a collectionView inside of a tableView. 如何将CollectionView数据设置为Collection tag.collection标签计数不固定。如何在CollectionView中集成cellForItemAt和numberOfItemsInSection。所以我在tableView内部有一个collectionView。 I would like to use the values from my array to populate each labels text inside each collectionViewCell. 我想使用数组中的值来填充每个collectionViewCell中的每个标签文本。 If I print the code below in collectionView cellForItemAt. 如果我在collectionView cellForItemAt中打印以下代码。

    class testViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {


        @IBOutlet weak var providerCategoryTableView: UITableView!

        let collectionReuseIdentifier = "selectServiceProviderCollectioncell" // Collection cell identifier in the storyboard
        let tableReuseIdentifier = "selectServiceProviderTableViewCell"

        var providerCategoryTableViewDictionary = [NSMutableDictionary]()
        var providerCategoryCollectionViewDictionary = [String:Any]()
        var providerCategoryDictionary = [[String:Any]]()


        var ServiceResponse:[[String:Any]] = {[id:1,provider_name:”Telephone”,providers:[{category_name:”Test1”,id:”1”}, {category_name:”Test2”,id:”2”}]], [id:2,provider_name:”MobileNumber”,providers:[{category_name:”Test3”,id:”1”}, {category_name:”Test2”,id:”2”}, {category_name:”Test4”,id:”4”}, {category_name:”Test5”,id:”5”}]]}


        var setIndexTag:Int = 0
        var cellForItemIndexTag:Int = 0
        var exapandTableViewArray = [Int]()

        override func viewDidLoad() {
            super.viewDidLoad()
            initControls()
        }

        // Expand function
        func isExpandable(tableViewHeight:Int) -> Bool {
            for item in exapandTableViewArray {
                if(tableViewHeight == item){
                    return true
                }
            }
            return false
        }

        // MARK: - Private
        func initControls(){
            providerCategoryTableView.tableFooterView = UIView()
            callSelectServiceProvidersAPI()
            addServiceProviderLabel.attributedText = GlobalFunctions().addNormalAndBoldText(normalText: NSLocalizedString("RecipientSelectServiceProvidersViewController.addServiceProviderNormalLabel", comment: ""), boldText: NSLocalizedString("RecipientSelectServiceProvidersViewController.addServiceProviderBoldLabel", comment: ""), fontSize : 16.0)
            DontSeeYourServiceUILabel.attributedText = GlobalFunctions().addNormalAndBoldText(normalText: NSLocalizedString("RecipientSelectServiceProvidersViewController.DontSeeYourServiceUINormalLabel", comment: ""), boldText: NSLocalizedString("RecipientSelectServiceProvidersViewController.DontSeeYourServiceUIBoldLabel", comment: ""),fontSize : 16.0)
            suggestAServiceUIView.layer.borderColor = UIColor( red: CGFloat(115/255.0), green: CGFloat(204/255.0), blue: CGFloat(215/255.0), alpha: CGFloat(1.0) ).cgColor

        }


        // MARK: - UITableView
        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return ServiceResponse.count
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: tableReuseIdentifier, for: indexPath) as! RecipientSelectServiceProviderTableViewCell
            let providerCategoryObject = selectServiceProviderResponse[indexPath.row]
            cell.categoryNameLabel.text = (providerCategoryObject["name"] as? String)!
            cell.categoryCollectionView.delegate = self
            cell.categoryCollectionView.dataSource = self
            cell.categoryCollectionView.tag = indexPath.row
            cell.categoryCollectionView.reloadData()
            return cell
        }

        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            if(isExpandable(tableViewHeight:indexPath.row)){
                return 60
            }else{
                return 120
            }
        }

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            let selectedCell = tableView.cellForRow(at: indexPath) as! RecipientSelectServiceProviderTableViewCell
            let UpBlueImage = UIImage(named: "up_blue_arrow")
            let UpBlueImageData = UIImagePNGRepresentation(UpBlueImage!)
            let SelectedImageData = UIImagePNGRepresentation((selectedCell.UpDownImageView.image)!)
            if (SelectedImageData == UpBlueImageData){
                exapandTableViewArray.append(indexPath.row)
                selectedCell.UpDownImageView.image = UIImage(named:"down_blue_arrow")
                self.CategoryTableView.beginUpdates()
                self.CategoryTableView.endUpdates()
             }else{
                if let index = exapandTableViewArray.index(of:indexPath.row) {
                    exapandTableViewArray.remove(at: index)
                }
                selectedCell.UpDownImageView.image = UIImage(named:"up_blue_arrow")
                self.CategoryTableView.beginUpdates()
                self.CategoryTableView.endUpdates()
            }
        }

        // MARK: - UICollectionView
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            //return collectioncategories.count
           /* if collectionView.tag == 0{
                return collectioncategories.count
            }else  if collectionView.tag == 1{
                return collectionSecondcategories.count
            }*/
            for obj in ServiceResponse {
                if collectionView.tag == setIndexTag {
                    let providers:[[String: Any]] = obj["providers"] as! [[String : Any]]
                    return providers.count
                 }
                setIndexTag = setIndexTag + 1
            }
            return 0
        }

        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionReuseIdentifier, for: indexPath) as! RecipientSelectServiceProviderCollectionViewCell
            //cell.categoryUILabel.text = collectioncategories[indexPath.row]
            /*if collectionView.tag == 0{
                cell.categoryUILabel.text = collectioncategories[indexPath.row]
            }else  if collectionView.tag == 1{
                cell.categoryUILabel.text = collectionSecondcategories[indexPath.row]
            }*/
            for obj in ServiceResponse {
                if collectionView.tag == cellForItemIndexTag {
                    let providers:[[String: Any]] = obj["providers"] as! [[String : Any]]
                    let data = providers[indexPath.row]
                    print("providers",providers[indexPath.row])
                     print("data",data)
                    for provider in providers {
                        print("cellForItemAt provider.name",provider["name"] as! String)
                        cell.categoryUILabel.text! = (provider["name"] as? String)!
                        print("cell.categoryUILabel.text",cell.categoryUILabel.text!)
                    }
                }
                cellForItemIndexTag = cellForItemIndexTag + 1
            }
            return cell
        }

      /*  func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeForItemAt indexPath: IndexPath) -> CGSize {
            let nbCol = 3
            let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
            let totalSpace = flowLayout.sectionInset.left + flowLayout.sectionInset.right + (flowLayout.minimumInteritemSpacing * CGFloat(nbCol - 1))
            let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(nbCol))
            return CGSize(width: size, height: size)
        }*/







I want 
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //return collectioncategories.count
       if collectionView.tag == 0{
            return collectioncategories.count
        }else  if collectionView.tag == 1{
            return collectionSecondcategories.count
        }
}

But 0,1....n collectionView.tag not fixed and inside array count also different.Please Its Urgent.Thanks

i have done a similar application where what we did is create one parent array ie 我做了一个类似的应用程序,我们所做的是创建一个父数组,即

var tableViewDataArray = [HomeDataHolder] () // which includes the type , sub category in my case myclass contains category name , category id and product array

after this add each category in to this array for me, added dataArry[banners,toppicks,.....] 在此之后,为我将每个类别添加到此数组中,添加了dataArry [banners,toppicks,.....]

this is how added class object to arraya 这是如何将类对象添加到arraya

if let categoryes = JSON["categories"] as? NSArray{
                for index in 0..<categoryes.count{
                    self.categoryArray.add(categoryes[index])
                }
                print(self.categoryArray)
                self.session.saveCategory(self.categoryArray)

                let catObject = HomeDataHolder(type:"CATEGORY").addCategoryes(categoryArray: self.categoryArray)
                self.tableViewDataArray.append(catObject)


            }

set tableview datasource as this array if you need different type design design different cells 如果您需要不同的类型设计,设计不同的单元格,则将tableview数据源设置为此数组

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let homeData = tableViewDataArray[indexPath.row] as! HomeDataHolder
    if homeData.type == "CATEGORY"{
        let cell = tableView.dequeueReusableCell(withIdentifier: "category_name_cell", for: indexPath) as! HomeCategoryTableViewCell
        cell.selectionStyle = .none
        let dataArray = homeData.dataArray
        cell.setProducArray(dataArray!)
        cell.delegate = self
        return cell
    }else if .......

in my HomeCategoryTableViewCell class 在我的HomeCategoryTableViewCell类中

func setProducArray(_ data:NSMutableArray){
    for index in 0..<data.count{
        dataArray.add(data[index])

    }

    colectionView.reloadData()
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return dataArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "home_categoryes_cellection_cell", for: indexPath) as! HomeCategoriesCollectionViewCell
    if let dataDictionary = dataArray[indexPath.row] as? NSDictionary{
        utility.setCornerRadius([cell.containerView], cornerRadies: 19)
        cell.categoryNameLabel.text = dataDictionary.getStringValue("name")
        print(dataDictionary.getStringValue("name"))

    }

    return cell
}

and my HomeCategoryTableViewCell contains a collection view cell.setProducArray(dataArray!) will change the datasource of the collectionview 并且我的HomeCategoryTableViewCell包含一个收集视图cell.setProducArray(dataArray!)将更改collectionview的数据源

In your cellForRow of the TableView access the collectionView with viewWithTag and then give it the indexPath.row in the accessiblityHint property and call reload. 在TableView的cellForRow中,使用viewWithTag访问collectionView,然后在accessiblityHint属性中为其指定indexPath.row并调用重新加载。 Then in the your numberOfSections, numberOfItems or cellForItem methods of collectionView you can access the accessiblityHint property and access your array's index to display the data you want. 然后,在collectionView的numberOfSections,numberOfItems或cellForItem方法中,您可以访问accessiblityHint属性并访问数组的索引以显示所需的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM