Как получить раздел UITableView изнутри дочернего UICollectionview

У меня есть UITableView с UICollectionView в каждом из его рядов, как показано на рисунке ниже.

виды коллекций внутри таблиц

источник: https://ashfurrow.com/blog/putting-a-uicollectionview-in-a-uitableviewcell-in-swift/

Целью моего приложения является отображение набора символов языка в каждой строке табличного представления. Каждый символ содержится в ячейке представления коллекции представления коллекции в соответствующей строке.

мое приложение

У меня проблема в том, что английский набор символов отображается для каждой строки таблицы.

Это связано с тем, что каждый коллекционный вид имеет только один раздел и, следовательно, каждый коллекционный вид использует один и тот же indexPath.section значение ноль.

Что мне нужно сделать, это получить значение сечения ячеек табличного представления, в котором находятся коллекции, и каким-то образом передать его

func collectionView(_ collectionView: UICollectionView,
                    cellForItemAt indexPath: IndexPath) -> UICollectionViewCell

I've tried several things but I can't find a way to access the tableview section value from the collectionview within it.

My code is a bit of a mess but the generally important parts are

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "HorizontalSlideCell", for: indexPath)

    return cell
}

...

func collectionView(_ collectionView: UICollectionView,
                    cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "InnerCollectionViewCell",
                                                  for: indexPath as IndexPath)

    //format inner collectionview cells

    //indexPath.section is the collectionview section index but needs to be its parent tableview section's index. How do I get it? 
    cellCharLabel?.text = Languages.sharedInstance.alphabets[indexPath.section].set[indexPath.row].char
    cellCharLabel?.textAlignment = .center
    cellCharLabel?.font = UIFont(name: "Helvetica", size: 40)

    cell.contentView.addSubview(cellCharLabel!)

    return cell
}

2 ответа

Решение

Вы можете установить collectionView тег, чтобы сделать это.CollectionView должно быть подвидом tableViewCell, Это collectionView может быть собственностью вашей настройки TableViewCell Кажется вы используете Prototype Cell,

class YourCustomizeTableViewCell: UITableViewCell {
   let collectionView: CollectionView
   ...
}



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

    let cell = tableView.dequeueReusableCell(withIdentifier: "HorizontalSlideCell", for: indexPath) as! YourCustomizeTableViewCell
   cell.collectionView.tag = indexPath.row

   return cell
}

...

func collectionView(_ collectionView: UICollectionView,
                    cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "InnerCollectionViewCell",
                                              for: indexPath as IndexPath)


//indexPath.section is the collectionview section index but needs to be its parent tableview section's index. How do I get it? 
cellCharLabel?.text = Languages.sharedInstance.alphabets[collectionView.tag].set[indexPath.row].char
 ...
return cell
}

Я предполагаю, что у вас есть пользовательский класс UITableViewCell с экземпляром UICollectionView, поэтому вам просто нужно передать ему индекс раздела при вызове cellForRowAtIndexPath.

Вам нужно будет сделать переменную в классе tableViewCell для хранения индекса раздела.

 class CustomTableViewCell: UITableViewCell {
      var sectionIndex:Int?

 }

Затем при вызове cellForRow... вы просто переходите в раздел к этой ячейке.

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "HorizontalSlideCell", for: indexPath) as CustomTableViewCell
    cell.sectionIndex = indexPath.section
    return cell
}

Не уверен, как вы загружаете данные в представления коллекций, поскольку вы не показываете это, но как только ваша ячейка табличного представления имеет раздел, вы можете сделать несколько вещей для загрузки ваших данных.

Дайте мне знать, если вам нужно больше деталей

Другие вопросы по тегам