为 tableview 单元内的 collectionview 加载更多功能

Posted

技术标签:

【中文标题】为 tableview 单元内的 collectionview 加载更多功能【英文标题】:Load more functionality for collectionview inside tableview cell 【发布时间】:2019-08-23 08:08:50 【问题描述】:

我想知道如何在 tableview 单元格内的集合视图中加载更多功能。由于集合视图滚动未启用。

在集合视图单元格中放置最后一个索引检查的代码会产生奇怪的行为,因为有时到达最后一个索引根本不会调用功能,有时它会在移动到其他单元格时加载更多内容。我知道这是由于 tableview 单元格而发生的。任何人都可以帮助我解决如何解决它。

这是我正在使用的代码:

//
//  JustForYouTableViewCell.swift
//  ShoppingPortal
//
//  Created by Faraz Haider on 10/07/2019.
//  Copyright © 2019 B2b. All rights reserved.
//

import UIKit
protocol JustForYouTableViewCellDelegate: class 
    func justForYouClickedWithItem(_ itemIndex:Int)
    func loadMoreDataForJustForYouWithPageNumber(pageNumber : Int, records: Int)



class JustForYouTableViewCell: BaseTableViewCell 

    @IBOutlet weak var justForYouCollectionView: UICollectionView!
    weak var delegate: JustForYouTableViewCellDelegate?
    var justForYouArray = [Product]()
    var cellHeight:CGFloat = 0
    var pageNumber = 1
    var currentRecordsCount = 0
    var totalNumberOfRecord = 0
    var isLoadMore = false
    var isReload = false

    @IBOutlet weak var collectionHeight: NSLayoutConstraint!
    override func awakeFromNib() 
        super.awakeFromNib()
        // Initialization code
    


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

        // Configure the view for the selected state
    

    override func updateCell(rowModel: BaseRowModel) 
        if !isReload
           justForYouArray = rowModel.rowValue as! [Product]
            pageNumber = rowModel.tag
            totalNumberOfRecord = rowModel.rowId
        

        currentRecordsCount = justForYouArray.count

        if(currentRecordsCount < totalNumberOfRecord)
            isLoadMore = true
        else
            isLoadMore = false
        
        self.delegate = rowModel.delegate as? JustForYouTableViewCellDelegate
        justForYouCollectionView.dataSource = self
        justForYouCollectionView.delegate = self
        justForYouCollectionView.isScrollEnabled = false
        cellHeight = rowModel.rowHeight

        NotificationCenter.default.addObserver(self, selector: #selector(doThisWhenNotify(notification:)), name: NSNotification.Name(rawValue: "post"), object: nil)

        self.collectionHeight.constant = self.justForYouCollectionView.collectionViewLayout.collectionViewContentSize.height;
        justForYouCollectionView.reloadData()
    

    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize 

        self.layoutIfNeeded()
        let contentSize = self.justForYouCollectionView.collectionViewLayout.collectionViewContentSize
        return CGSize(width: contentSize.width, height: contentSize.height + 20) // 20 is the margin of the collectinview with top and bottom
    


    @objc func doThisWhenNotify(notification : NSNotification) 
        if let info = notification.userInfo as? NSDictionary
            if let id = info["product"] as? [Product]
                justForYouArray.append(contentsOf:id)
            
            isReload = true
            let homeVC = self.viewController as? HomeVC
            homeVC?.dashboardTblView.reloadData()

        
    

    @IBAction func moreButtonClicked(_ sender: Any) 

        let viewController:MoreProductsVC = UIStoryboard(name: "HomeModule", bundle: nil).instantiateViewController(withIdentifier: "MoreProductsVC") as! MoreProductsVC
        viewController.selectedState = .SelectedStateJustForYou
        self.viewController?.navigationController?.pushViewController(viewController, animated: true)
    

extension JustForYouTableViewCell: UICollectionViewDataSource,UICollectionViewDelegate 

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
        return justForYouArray.count
    

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

        let cell : JustForYouCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "JustForYouCollectionViewCell", for: indexPath) as! JustForYouCollectionViewCell


        let deals = justForYouArray[indexPath.row]
        cell.titleLabel.text = Utility.checkEmptyString(deals.name)

        if deals.productImage.count>0
            if let imageUrl = deals.productImage[0].url
                let url = URL(string: imageUrl)
                let image = UIImage(named: "placeholder")
                cell.dealsImageView.kf.setImage(with: url, placeholder: image)
            
        

        if deals.setPriceOption == 1
            cell.priceLabel.text = String(format: "%@ %d - %d %@", Utility.checkEmptyString(deals.fobPriceName),deals.min,deals.max,Utility.checkEmptyString(deals.tradeUnitName))
        else
            if deals.productDifferencePriceQuantity.count>0
                cell.priceLabel.text = String(format: "%@ %d - %d %@", "USD",deals.productDifferencePriceQuantity[0].mOQ,deals.productDifferencePriceQuantity[0].fOBPrice,Utility.checkEmptyString(deals.tradeUnitTypeName))
            else
                cell.priceLabel.text = ""
            

        

        // Check if the last row number is the same as the last current data element
        if indexPath.row == self.justForYouArray.count - 1 && self.isLoadMore 
            updateNextSet()
        

        return cell
    

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) 
        print(indexPath.row)
        let deals = justForYouArray[indexPath.row]
        let storyBoard: UIStoryboard = UIStoryboard(name: "HomeModule", bundle: nil)
        let newViewController = storyBoard.instantiateViewController(withIdentifier: "ProductDetailVC") as! ProductDetailVC
        if (deals.productId != nil)
            newViewController.selectedProductId = deals.productId
            self.viewController?.navigationController?.pushViewController(newViewController, animated: true)
        

    



    func updateNextSet()
            pageNumber += 1
            self.delegate?.loadMoreDataForJustForYouWithPageNumber(pageNumber: pageNumber, records: currentRecordsCount)
            isLoadMore = false
    



extension JustForYouTableViewCell: UICollectionViewDelegateFlowLayout 
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 
        let spacing : CGFloat = (collectionViewLayout as? UICollectionViewFlowLayout)?.minimumInteritemSpacing ?? 0.0
        let widthPerItem = (collectionView.frame.height  - spacing * 2) / 3
        return CGSize(width: screenWidth/2, height: 200)
    

【问题讨论】:

为了简化你可以用滚动视图替换你的tableview 现在做不到。基本上这是包含collectionview的单元格之一。其他单元格与 tableview 绑定。 我不明白为什么人们投票反对它。这不是一个正确的问题吗?? 【参考方案1】:

好的,我确实从另一个来源得到了答案?,对于正在寻找解决方案的人来说,我所做的是我将滚动视图委托滚动视图确实结束了拖动,并且我设置了一旦你达到滚动视图最大高度 - 高度我的最后一个单元格我确实加载了更多。谢谢大家

**

代码 sn-p

**

func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool)

// UITableView only moves in one direction, y axis
let currentOffset = scrollView.contentOffset.y
let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height

// Change 10.0 to adjust the distance from bottom
if maximumOffset - currentOffset <= 235 
    if (self.isLoadMore)
        self.isFirstTime = false
        justForYouPageNumber += 1
        callServiceFoNewArrivals(withPageNumber: justForYouPageNumber, andRecords: 10)
    


   

【讨论】:

以上是关于为 tableview 单元内的 collectionview 加载更多功能的主要内容,如果未能解决你的问题,请参考以下文章

单元格获取其前一个单元格的索引 - Tableview 内的 Collectionview

为啥当我向下滚动iOS(tableView内的collectionview)时取消选择单元格?

UITableViewCell内的UICollectionView如何根据屏幕大小调整tableview单元格高度

从 collectionView 单元格中获取和更新 UITableView 单元格单击

如何在tableview单元格中设置视图内的视图的圆角半径?

UITableView 内的 CollectionView 单元格重复