即使显示为选中状态,UITableViewCell内的UICollectionView始终返回空

时间:2019-04-18 23:51:26

标签: ios swift uicollectionview

我正在UITableViewCell内使用UICollectionView。我可以选择UICollectionView中的单元格。但是当我尝试获取UICollectionView或选定的单元格时,结果始终为null。我已经坚持了很长时间。我在下面提供了我的代码,供您参考。

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 :(得分:0)

您正在尝试在willMove(toParent parent: UIViewController?)中获得可重复使用的单元格,但这不会返回预期的单元格。

您需要使用indexPath获取单元格。

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

答案 1 :(得分:0)

@andyPaul,对,您正在willMove(toParent parent:UIViewController?)中生成新单元格。取而代之的是,当用户从tableView单元格类中选择任何单元格到控制器时,您必须传递indexpath pf集合视图。

现在您可以从此链接中阅读有关类型别名的TypeAlias:-https://www.programiz.com/swift-programming/typealias

  1. 像这样在tableViewCell类的上方创建typeAlias:-

    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 方法分配值时,它可以检查是否在哪个控制器中返回该值。

  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
    }