如何在动态uitableview中创建动态uicollectionview

时间:2016-01-14 09:34:05

标签: ios swift uicollectionview

我是swift以及iOS开发的新手。我想在swift中创建包含集合视图的tableview。我能够做到这一点,但我的问题出现在集合视图中的项目数量和没有。 tableview中的行取决于我正在检索的json数据。我无法在集合视图中编写项目数。我正在为tableviewcell和collectionviewcell使用自定义单元类。如何更改表的collectionview单元格中每个表行的数据不同。集合视图委托的代码

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

        return array_servicelist.objectAtIndex(something).valueForKey("subCategoryList")!.count
}

func collectionView(collectionView: UICollectionView,
    cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collectioncell",
            forIndexPath: indexPath) as! ServiceCollectionViewCell

        let str :String = "\(array_servicelist.objectAtIndex(indexPath.section).valueForKey("subCategoryList")!.objectAtIndex(indexPath.item).valueForKey("phoneImageUrl") as! String)"
        cell.serviceImage.image = UIImage(data: NSData(contentsOfURL: NSURL(string: str)!)!)
        cell.serviceName.text = "\(array_servicelist.objectAtIndex(indexPath.section).valueForKey("subCategoryList")!.objectAtIndex(indexPath.item).valueForKey("categoryName") as! String)"

        return cell
}

tableview委托代码

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return array_servicelist.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("tablecell", forIndexPath: indexPath)

    return cell
}

 func tableView(tableView: UITableView,
    willDisplayCell cell: UITableViewCell,
    forRowAtIndexPath indexPath: NSIndexPath) {

        guard let tableViewCell = cell as? ServiceTableViewCell else { return }

        tableViewCell.setCollectionViewDataSourceDelegate(self, forRow: indexPath.row)

}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

1 个答案:

答案 0 :(得分:0)

This is an example of collectionView inside a collectionViewCell, but the same applies to tableView's as well. The datasource is abstracted, each cell has its own datasource. You should be able to figure out your problem looking at this.

https://github.com/irfanlone/Collection-View-in-a-collection-view-cell

Using a collection view has certainly some advantages over tableviews in this case. Other useful Links:

Tutorial : https://ashfurrow.com/blog/putting-a-uicollectionview-in-a-uitableviewcell-in-swift/

Source Code: https://github.com/ashfurrow/Collection-View-in-a-Table-View-Cell

Hope that helps!!