简体   繁体   中英

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. I would like to use the values from my array to populate each labels text inside each collectionViewCell. If I print the code below in 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,.....]

this is how added class object to 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

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

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

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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