【问题标题】:Getting indexPath of tableView inside tableViewCell file during cell creation/dequeueing在单元格创建/出列期间获取 tableViewCell 文件中 tableView 的 indexPath
【发布时间】:2019-05-29 02:46:48
【问题描述】:

我正在创建一个充满月历的可滚动视图。我正在使用集合视图在充满日历的表视图中显示日历。所以每个表格视图单元格是一个特定月份的日历,每个集合视图单元格是一天。我有一个来自视图控制器的 tableview 单元格的单独 swift 文件。由于每个 tableview 单元格看起来会有所不同(因为不同的月份),因此 tableview 单元格需要知道它在 dequeque 单元格函数中创建期间放置在 tableview 内的哪一行。

tableView.dequeueReusableCell(withIdentifier: "CalendarTableViewCell", for: indexPath)

我需要在 tableview 单元格文件内的“for:indexPath”参数中获取 indexPath,因为 tableview 单元格内的 collectionview 是在 tableview 单元格出列时创建的。集合视图的内容取决于它所在的 tableview 行。那么如何获取该参数?

抱歉,解释太长了,如果可能的话,请帮忙。谢谢!

【问题讨论】:

  • 为什么单元格需要知道它在哪一行?它可能需要知道它的月份或年份,但即便如此,您也可以实例化一个集合视图数据源对象并将其传递给单元格
  • 是的,您可以这样做,但如果您需要这样做,您的应用架构可能存在缺陷
  • 嗯..是否可以在开始在单元格中创建诸如集合视图之类的内容之前将数据传递给单元格?我不完全确定您在第一条评论中的意思,但我需要该行,因为第一行是当前月份的日历,第二行是上个月的日历,等等。

标签: ios swift xcode uitableview uicollectionview


【解决方案1】:

在 UITableViewCell 子类中创建一个数组,并在集合视图数据源方法中使用该数组。

class MonthCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    let datesArray = [String]()
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return datesArray.count
    }
}

tableView cellForRowAt 方法中分配日期值并重新加载collectionView

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell") as! MonthCell
    cell.datesArray = []//dates based on indexPath
    cell.collectionView.reloadData()
    return cell
}

或者

tableView cellForRowAt方法中分配对表格视图单元格索引路径的引用

class MonthCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    var tableIndexPath:IndexPath?
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let tableIndexPath {
            // return value based on tableIndexPath
        } else {
            return 0
        }
    }
}

//cellForRowAt

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MonthCell") as! MonthCell
    cell.tableIndexPath = indexPath
    cell.collectionView.reloadData()
    return cell
}

【讨论】:

  • 非常感谢拉杰什!这就是我一直在寻找的,我想我会使用这个解决方案。我计划在滚动到每个表格视图后,在 cellForRowAt 函数之外的某个函数中更改集合视图的内容,以便它们都是可见的单元格,但我认为你的更干净。
猜你喜欢
  • 2017-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-07
相关资源
最近更新 更多