【问题标题】:Collection view inside table view表视图内的集合视图
【发布时间】:2019-05-29 16:02:34
【问题描述】:

我有以下问题。 在我的项目中,我有一个表格视图,其中包含多个部分,每个部分都有一行。内行我有一个集合视图。 集合视图项目计数取决于集合所在的部分。但是当我为集合视图调用 func numberOfItemsInSection 时,我不明白如何访问部分编号。

这是我的代码:

ViewController.swift

func numberOfSections(in tableView: UITableView) -> Int { 
return data.count
}

TableCell.swift

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    //TODO ?????? How can i get here section of table view
}

谢谢!

【问题讨论】:

  • 如果您在部分中只有一行并且每一行中只有一个UICollectionView,为什么不只使用一个UICollectionView 来填充您的数据。 link 这是一个很长的教程,但也许可以帮助您有效地使用UICollectionView

标签: swift


【解决方案1】:

在 UITableViewCell 子类中创建一个数组并在 collectionview 数据源方法中使用该数组

class CustomCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    var collectionData = [String]()

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return collectionData.count
    }
}

tableView cellForRowAt 方法中为数组赋值并重新加载集合视图

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell") as? CustomCell
    cell?.collectionData = []//assign data here based on indexPath.section
    cell?.collectionView.reloadData()
    return cell!
}

【讨论】:

  • 谢谢,工作!但是在集合视图中重新加载数据后,应用启动时屏幕上的那些行不应用集合视图布局:(
【解决方案2】:

在这里您可以使用面向对象的方法,在您的表格视图单元格中创建一个变量tableSectionNumber。喜欢

class YourCell: UITableViewCell {
    public var tableViewSectionNumber: Int = 0;
....

现在在collectionViewnumberOfItemsInSection方法中,你可以访问它

 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//TODO ?????? How can i get here section of table view
  self.tableViewSectionNumber // its here
 }

现在您可以在 ViewController 的单元格中设置此值,当您在 TableView cellForRowItem 方法中填充单元格时,喜欢

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! YourCell
    cell.tableViewSectionNumber = indexPath.section // here you set the section number in cell
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多