简体   繁体   中英

collectionView numberOfItemsInSection in UITableviewCell

I made one collectionView inside the tableView cell

I registered all delegates and protocols and in most cases everything works fine

the problem is that the collectionView must dynamically generate cells from the server response

I installed a counter on the top of the collection that shows how many cells there are (also dynamically updated)

if the collection is in the field of view when the screen is loaded, the cells are loaded

if it is necessary to complete the collection, it is empty, although the counter indicates the presence of elements.

I can not quite understand why. Code below

code form VC:

 let realPfotoCell = tableView.dequeueReusableCell(withIdentifier: 
"RealPhoto", for: indexPath)
            as! RealPhotoCarInfoTableViewCell
        realPfotoCell.delegate = self


        realPfotoCell.model = self.rPhoto
        if(self.rPhoto?.data != nil){
            realPfotoCell.RPhotoCount.text = String(self.rPhoto.data!.count)
        }



        cell = realPfotoCell
        cell.selectionStyle = UITableViewCell.SelectionStyle.none
    }

code from tableViewCell :

    var model: RealPhoto!

    func setCollectionViewDataSourceDelegate(dataSourceDelegate: UICollectionViewDataSource & UICollectionViewDelegate, forRow row: Int) {
        MyCollection.delegate = self
        MyCollection.dataSource = self
        MyCollection.reloadData()

    }

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
MyCollection.reloadData()
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

    }



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

        if (self.model?.data?.count != nil){
            print("Photos here")
            print(self.model?.data!.count as Any)
        } else {
            print("No photos")
        }

        return self.model?.data?.count ?? 0

    }

Please make sure the ReloadData() will be call when your server response will come.

   //Server Response
    MyCollection.delegate = self
    MyCollection.dataSource = self
    MyCollection.reloadData()

resolved

1st on tableview cell create this function:

func collectionReloadData(){
        DispatchQueue.main.async(execute: {
            self.collectionView.reloadData()
        })
    }

then call it from

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

realPfotoCell.collectionReloadData()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM