【问题标题】:In iOS Swift integrate Different array for CollectionView Inside TableView in Swift 4在 iOS Swift 中,在 Swift 4 中的 TableView 中为 CollectionView 集成不同的数组
【发布时间】:2018-08-19 08:01:57
【问题描述】:

如何将 CollectionView 数据设置为 Collection 标签。collection 标签计数不固定。如何在 CollectionView 中集成 cellForItemAt 和 numberOfItemsInSection。所以我在 tableView 中有一个 collectionView。我想使用我的数组中的值来填充每个 collectionViewCell 中的每个标签文本。如果我在 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

【问题讨论】:

  • 每个表格视图单元格都应该是该单元格中collectionview的collectionview数据源
  • But.how to inrate data in collectionview cell
  • 将相关数组设置为 UITableViewCell 子类的属性,并让该子类提供集合视图单元格

标签: ios swift


【解决方案1】:

我做了一个类似的应用程序,我们所做的是创建一个父数组 即

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

在此之后为我将每个类别添加到此数组中,添加 dataArry[banners,toppicks,.....]

这是将类对象添加到数组a的方式

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)


            }

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

在我的 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
}

我的 HomeCategoryTableViewCell 包含一个集合视图 cell.setProducArray(dataArray!) 将更改集合视图的数据源

【讨论】:

【解决方案2】:

在 TableView 的 cellForRow 中,使用 viewWithTag 访问 collectionView,然后在 accessiblityHint 属性中为其提供 indexPath.row 并调用 reload。然后在 collectionView 的 numberOfSections、numberOfItems 或 cellForItem 方法中,您可以访问 accessiblityHint 属性并访问数组的索引以显示您想要的数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多