首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >collectionView.collectionViewLayout.invalidateLayout()

collectionView.collectionViewLayout.invalidateLayout()
EN

Stack Overflow用户
提问于 2020-04-28 13:31:57
回答 1查看 1.5K关注 0票数 3

我在TableView中有一个动态TableView,当我添加invalidateLayout时有一个错误(图片如下),但是如果我删除invalidateLayout,前四个单元格是隐藏的,布局没有正确显示,视频

,请帮助我搜索整个堆栈,但是没有什么能帮助我,谢谢

如果您需要测试项目

MainViewController

代码语言:javascript
运行
复制
class ViewController: UIViewController, UIScrollViewDelegate {


  override func viewDidLoad() {
        super.viewDidLoad()
        setting()
    }

  func setting(){

   getData()

   tableView.dataSource = self
   tableView.delegate = self

   tableView.estimatedRowHeight = UITableView.automaticDimension 
   tableView.rowHeight = UITableView.automaticDimension    

  }

         //load data
   func pagination(_ completion: (()->())?){

      SmartNetworkSevrice.getGoods(with: url) { [unowned self] (data) in
         guard data.modals.count > 0 else {
             self.tableView.tableFooterView = nil
             return
         }

         self.goods.append(contentsOf: data.modals)
         self.offSet += data.modals.count
         DispatchQueue.main.async {
             let indexPath = IndexPath(row: 0, section: 0)
             self.tableView.tableFooterView = nil
             if self.goods.count == data.modals.count || self.isRefresh {
                self.tableView.reloadRows(at: [indexPath], with: .none)
             } else {
                if let cell = self.tableView.cellForRow(at: indexPath) as? TVCellGoods {
                    UIView.performWithoutAnimation {
                        self.tableView.beginUpdates()
                        cell.insertGoods(data.modals)
                        cell.layoutIfNeeded()
                        cell.collectionViewHeight.constant = cell.collectionView.collectionViewLayout.collectionViewContentSize.height
                        self.tableView.endUpdates()
                     }

                }
             }
            completion?()
         }
     }

     // define bottom of tableView
    func scrollViewDidScroll(_ scrollView: UIScrollView) {

        guard scrollView == self.tableView else {  return }
        if (!isMoreDataLoading) {

            // Вычислить позицию длины экрана до нижней части результатов
            let scrollViewContentHeight = scrollView.contentSize.height
            let scrollOffsetThreshold = scrollViewContentHeight - scrollView.bounds.size.height
            if(scrollView.contentOffset.y > scrollOffsetThreshold && scrollView.isDragging) {
                isMoreDataLoading = true
                self.tableView.isScrollEnabled = false;
                self.tableView.isScrollEnabled = true;
                pagination(nil)
            }
        }

       }

    }

extension ViewController: UITableViewDataSource {


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "goods", for: indexPath) as? TVCellGoods else { return UITableViewCell() }
              guard bestGoods.count != 0, goods.count != 0 else { return UITableViewCell() }
            cell.delegate = self
            cell.configure(bestGoods, goods, categories)
            // автообновление высоты
            self.tableView.beginUpdates()
            cell.collectionViewHeight.constant = cell.collectionView.collectionViewLayout.collectionViewContentSize.height
            self.tableView.endUpdates()
            return cell 
    }

}

extension ViewController: UITableViewDelegate, CallDelegate {

    func callMethod() {}

    func callMethod(push vc:UIViewController) {
        self.navigationController?.pushViewController(vc, animated: true)
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            return UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
            return UITableView.automaticDimension
    }

}

TableViewCell与collectionView

代码语言:javascript
运行
复制
class TVCellGoods: UITableViewCell {

    @IBOutlet weak var collectionView:UICollectionView!
    @IBOutlet weak var collectionViewHeight:NSLayoutConstraint!

    weak var delegate:CallDelegate?
    var bestGoods = [Goods]() // лучшие товары
    var goods = [Goods]() // все товары
    var categories = [Menu]()

    override func layoutSubviews() {
       super.layoutSubviews()
       self.collectionView.collectionViewLayout.invalidateLayout()
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.tag = 2
        collectionView.isScrollEnabled = false

    }

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

        // Configure the view for the selected state
    }

    func configure(_ best:[Goods],_ goods:[Goods], _ category:[Menu]) {

        self.bestGoods = best
        self.goods = goods
        self.categories = category
        self.collectionView.reloadData()

    }

    func insertGoods(_ data:[Goods]) {

        self.goods.append(contentsOf: data)
        let count = self.bestGoods.count + self.categories.count  + self.goods.count
        let indexPaths = ((count - data.count) ..< count)
            .map { IndexPath(row: $0, section: 0) }
        self.collectionView.performBatchUpdates({
            self.collectionView.insertItems(at: indexPaths)
        }, completion: nil)

    }

}

和CollectionViewCell

代码语言:javascript
运行
复制
class CVCellGoods: UICollectionViewCell {

    @IBOutlet weak var bgView: UIView!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var title: UILabel!
    @IBOutlet weak var price: UILabel!
    @IBOutlet weak var delivery: UIImageView!
    @IBOutlet weak var premium: UIImageView!

    override func prepareForReuse() {
        super.prepareForReuse()
        delivery.image = nil
        premium.image = nil
        title.text = nil
        price.text = nil
        imageView.image = nil
        imageView.sd_cancelCurrentImageLoad()
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        imageView.backgroundColor = UIColor(red: 215/255, green: 215/255, blue: 215/255, alpha: 1)

        self.contentView.layer.cornerRadius = 5
        self.contentView.layer.masksToBounds = true

        self.layer.shadowColor = UIColor.black.cgColor
        self.layer.shadowOffset = CGSize(width: 0, height: 0.5)
        self.layer.shadowRadius = 1
        self.layer.shadowOpacity = 0.3
        self.layer.masksToBounds = false
        self.layer.shouldRasterize = true
        self.layer.rasterizationScale = UIScreen.main.scale

    }

}

编辑

如果我用

代码语言:javascript
运行
复制
    self.collectionView.performBatchUpdates({
            self.collectionView.insertItems(at: indexPaths)
        }, completion: { _ in
            self.collectionView.reloadItems(at: indexPaths)
        })

使用invalidateLayout,我在屏幕底部得到一个空空间。

但是如果我删除invalidateLayout,我就错了布局

如果您的不像我的那样,那么就放弃使用改进的项目

第二版

我注意到iPhone 11 Pro上有一个缩进,iPhone 11 Pro Max上一切都很好。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-09 00:34:09

更新:我在iPhone SE、11和11 Max的模拟器上验证了这一点,在集合视图的末尾没有死空间。

我的模拟器被设置为黑暗模式,以显示集合视图的底部仅够加载图标。

我必须做一些改变才能使它的尺寸合适。首先,我更改了insertGoods类中的TVCellGoods函数,使其仅在插入后重新加载新添加的项,并且列表顶部不再有缺少的项:

代码语言:javascript
运行
复制
    self.collectionView.performBatchUpdates({
        self.collectionView.insertItems(at: indexPaths)
    }, completion: { _ in
        self.collectionView.reloadItems(at: indexPaths)
    })

一个大问题是设置tableView单元格的估计行高度。我已经删除了estimatedHeightForRowAt覆盖,并用以下内容替换了您的heightForRowAt

代码语言:javascript
运行
复制
   func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        if indexPath.row == 0 {
            return (tableView.frame.width / 2.5) + 20
        } else if indexPath.row == 1 {
            return 70
        } else {
            guard let cell = tableView.cellForRow(at: indexPath) as? TVCellGoods else { return UITableView.automaticDimension }
//            print(cell.collectionViewHeight.constant)
            return cell.collectionViewHeight.constant
        }
    }

我还必须在您的layoutIfNeeded扩展中将cellForRow添加到您的cellForRow:

代码语言:javascript
运行
复制
self.tableView.beginUpdates()
cell.collectionViewHeight.constant = cell.collectionView.collectionViewLayout.collectionViewContentSize.height
self.tableView.endUpdates()
cell.collectionView.layoutIfNeeded()
self.tableView.layoutIfNeeded()

最后,在使layoutSubviews中的布局无效之后,我不得不更新您的TVCellGoods以分配正确的高度。

代码语言:javascript
运行
复制
override func layoutSubviews() {
    super.layoutSubviews()

    self.collectionView.collectionViewLayout.invalidateLayout()

    self.collectionViewHeight.constant = self.collectionView.collectionViewLayout.collectionViewContentSize.height
}

下面是更新的源代码:https://drive.google.com/open?id=1ldr4Ml2prZKmr1C4i1s5Sg7LvvxL7-jO

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61481436

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档