UICollectionView внутри UITableViewCell всегда возвращается пустым, даже если отображается как выбранное - PullRequest
0 голосов
/ 19 апреля 2019

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

class WeekDaysSelCell: UITableViewCell,UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {

    var weekdays = ["S", "M", "T", "W", "T", "F", "S"]

    var weekdaysSelected = [String]()

    @IBOutlet var weeklyDaysColView: UICollectionView!

    override func awakeFromNib() {
        super.awakeFromNib()
        self.weeklyDaysColView.delegate = self
        self.weeklyDaysColView.dataSource = self
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 7
    }

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

        let cell : WeekDaysCollCell = weeklyDaysColView.dequeueReusableCell(withReuseIdentifier: "weekday", for: indexPath) as! WeekDaysCollCell

        cell.weekDayLabel.text = weekdays[indexPath.row]
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let cell : WeekDaysCollCell = self.weeklyDaysColView.cellForItem(at: indexPath) as! WeekDaysCollCell
        if (cell.backgroundColor == UIColor.gray) {
            cell.backgroundColor  = UIColor.clear
            weekdaysSelected.removeAll { $0 == String(indexPath.row)}
            //print("Removed from weekdaysSelected:", indexPath.row)
        } else {

            cell.backgroundColor = UIColor.gray
            cell.isSelected = true
            //weeklyDaysColView.selectItem(at: indexPath, animated: true, scrollPosition: [])
            weekdaysSelected.append(String(indexPath.row))
            //print("Added to weekdaysSelected:", indexPath.row)
        }
    }
}

// Trying to get the collection view from inside a willMove(toParent parent: UIViewController?) method. 

    override func willMove(toParent parent: UIViewController?) {
            super.willMove(toParent: parent)
            if parent == nil
            {

                if let delegate = self.delegate {
                print("Inside If condition")

                // Code that i use to get the cell 
                let cell3 = tableView.dequeueReusableCell(withIdentifier: "cell3") as! WeekDaysSelCell

                    print(cell3.weekdaysSelected)

                    print(cell3.weeklyDaysColView.indexPathsForSelectedItems)

                    // Trying to pass selected cells
                    //delegate.repeatCustomSelection(selectedIdx: String(lastSelection.row),repeatCustomSel: repeatCustomSelection)
                }
            }
        }

Ответы [ 2 ]

0 голосов
/ 19 апреля 2019

@ andyPaul, верно, что вы генерируете новую ячейку в willMove (toParent parent: UIViewController?).Вместо этого вы должны передать представление pp indexpath pf, когда пользователь выбирает какую-либо ячейку для вашего контроллера из класса ячеек tableView.

Теперь, что такое TypeAlias, вы можете прочитать по этой ссылке о псевдониме типа: - https://www.programiz.com/swift-programming/typealias

  1. Создайте typeAlias ​​выше вашего класса tableViewCell следующим образом: -

    typealias closureBlock = (_ isCapture : AnyObject?) ->()
    
     class tableViewCellClass: UITableViewCell {
    
      var callBack: closureBlock?
    
      override func awakeFromNib() {
          super.awakeFromNib()
          // Initialization code
      }
    
  2. Просто перейдите в метод CollectionView didSelectItemAt и используйте этот код после кодирования

      func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    
      let cell : WeekDaysCollCell = self.weeklyDaysColView.cellForItem(at: indexPath) as! WeekDaysCollCell
      if (cell.backgroundColor == UIColor.gray) {
          cell.backgroundColor  = UIColor.clear
          weekdaysSelected.removeAll { $0 == String(indexPath.row)}
          //print("Removed from weekdaysSelected:", indexPath.row)
      } else {
    
          cell.backgroundColor = UIColor.gray
          cell.isSelected = true
          //weeklyDaysColView.selectItem(at: indexPath, animated: true, scrollPosition: [])
          weekdaysSelected.append(String(indexPath.row))
          //print("Added to weekdaysSelected:", indexPath.row)
       }
    
         guard let callBackClosure = self.callBack else {
             return
         }
         callBackClosure(indexPath as AnyObject)
         // You can pass any value here either indexpath or Array.
       }                  
    }
    
  3. Теперь вам нужно инициализировать это закрытие так,что он может проверить, в каком контроллере он будет возвращать значение при назначении значения из CollectionView didSelectItemAt Method.

  4. Перейти к вашему ViewController Класс, в который вы добавили таблицу и их источники данных.

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
         //You have to pass your tableview Cell Instance here and their reuse Identifier
        let cell = tableView.dequeueReusableCell(withIdentifier: "tableViewCellClass", for: indexPath) as! tableViewCellClass
    
         cell.callBack = { [weak self] (selectedIndexPath) -> ()in
          // You will get the current selected index path of collection view here, Whenever you pass any index path from collectionView did SelectItem Method.
            print(selectedIndexPath)
        }
        return cell
    }
    
0 голосов
/ 19 апреля 2019

Вы пытаетесь получить повторно используемую ячейку в willMove(toParent parent: UIViewController?), это не вернет вам ожидаемую ячейку.

Вам нужно получить ячейку, используя indexPath.

func cellForRow(at indexPath: IndexPath) -> UITableViewCell?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...