【问题标题】:Swift: How to clear collectionView for reuse in a collectionViewCellSwift:如何清除 collectionView 以便在 collectionViewCell 中重用
【发布时间】:2020-11-28 09:14:09
【问题描述】:

我有一个位于 collectionViewCell 内的 collectionView,而在重用单元格时,collectionView 没有被正确清除。

代码:

class TweetCell: UICollectionViewCell {

    lazy var mediaCollectionView: UICollectionView = {
        let size = NSCollectionLayoutSize(
            widthDimension: NSCollectionLayoutDimension.fractionalWidth(1),
            heightDimension: NSCollectionLayoutDimension.fractionalHeight(1)
        )
        
        let item = NSCollectionLayoutItem(layoutSize: size)
        let group = NSCollectionLayoutGroup.horizontal(layoutSize: size, subitem: item, count: 1)
        let section = NSCollectionLayoutSection(group: group)
        section.interGroupSpacing = 4
        section.orthogonalScrollingBehavior = .paging
        
        let layout = UICollectionViewCompositionalLayout(section: section)
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.translatesAutoresizingMaskIntoConstraints = false
        cv.dataSource = self
        cv.delegate = self
        cv.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        return cv
    }()

    var tweet: Tweet? {
        didSet {
            if let tweet = tweet {

                //Setup other UI elements
                nameLabel.text = tweet.name ?? ""
                twitterHandleLabel.text = tweet.twitterHandle ?? ""
                profileImageView.sd_setImage(with: profileImageUrl) 
            }
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
    
        setupViews()
    }
 
    func setupViews() {
    
 
        let mainStack = UIStackView(arrangedSubviews: [
            userHStack,
            mediaCollectionView,
            bottomHStack
        ])
    
        mainStack.axis = .vertical
        mainStack.translatesAutoresizingMaskIntoConstraints = false
    
        addSubview(mainStack)
        mainStack.topAnchor.constraint(equalTo: topAnchor).isActive = true
        mainStack.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        mainStack.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        mainStack.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
    
        //Must lower priority otherwise autolayout will complain
        heightConstraint = mediaCollectionView.heightAnchor.constraint(equalToConstant: 0)
        heightConstraint.priority = UILayoutPriority(999)
    
    }

    override func prepareForReuse() {
        super.prepareForReuse()
    
        mediaCollectionView.reloadData()
        tweet = nil
    }
} 

extension TweetCell: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource  {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return tweet?.mediaArray?.count ?? 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        cell.backgroundColor = .systemPink
        return cell
    }
}

//HomeController that displays the feed
class HomeController: UIViewController {

    lazy var collectionView: UICollectionView = {
        let size = NSCollectionLayoutSize(
            widthDimension: NSCollectionLayoutDimension.fractionalWidth(1),
            heightDimension: NSCollectionLayoutDimension.estimated(500)
        )
        
        let item = NSCollectionLayoutItem(layoutSize: size)
        let group = NSCollectionLayoutGroup.horizontal(layoutSize: size, subitem: item, count: 1)
        
        let section = NSCollectionLayoutSection(group: group)
        
        let layout = UICollectionViewCompositionalLayout(section: section)
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.translatesAutoresizingMaskIntoConstraints = false
        cv.dataSource = self
        cv.delegate = self
        cv.register(TweetCell.self, forCellWithReuseIdentifier: "cell")
        return cv
    }()
    
    var tweets: [Tweet]?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupViews()
        fetchData()
    }
    
    func fetchData() {
        let accessToken = UserDefaults.standard.string(forKey: Constants.UserDefaults.UserAccessTokenKey) ?? ""
        let secretToken = UserDefaults.standard.string(forKey: Constants.UserDefaults.UserSecretTokenKey) ?? ""
                
        TwitterClient.shared.fetchHomeTimeline(accessToken: accessToken, secretToken: secretToken) { (tweets) in
            self.tweets = tweets
            
            DispatchQueue.main.async {
                self.collectionView.reloadData()
            }
        }
    }
    
    
    func setupViews() {

        view.addSubview(collectionView)
        collectionView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    }
    
    
}

extension HomeController: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return tweets?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! TweetCell
        cell.tweet = tweets?[indexPath.item]
        return cell
    }
}

如果我将numberOfItemsInSection 硬编码为随机整数,mediaCollectionView 会正确显示单元格的数量。但是,当动态设置为tweet?.mediaArray?.count 时,单元格的数量不再正确。我相信这是由于 collectionViewCell 的重用,因为当我滚动浏览 collectionView 时,这些单元格的计数开始跳跃。

如何正确重置 TweetCell 中的 collectionView?

更新:

尝试 2:-

override func prepareForReuse() {
    
    mediaCollectionView.reloadData()
    tweet = nil
    super.prepareForReuse()
}

上面的效果不太好。

【问题讨论】:

  • 尝试做prepareForResuse在顶层cellForItemAt做的事情
  • @gkpln3 不太明白,能解释一下吗?
  • prepareForReuse 在 TweetCell 出队时被调用。在设置推文模型对象后,也不会重新加载 mediaCollectionView。请给我完整的代码好吗?
  • @ezaji 我已经更新了所有我认为相关的代码。为简洁起见,在 TweetCell 中省略了 UI 约束代码。
  • 首先,我认为您应该从prepareForReuse() 中删除mediaCollectionView.reloadData(),而不是tweet = nil,尝试将各个属性设置为nil,例如profileImageView.image = nil

标签: ios swift


【解决方案1】:

嗯。我认为您必须在单元内实现常规协议并重构所有代码。

我的意思是 UICollectionViewDelegate(或 flynDelegate)和 UICollectionViewDataSource。

class TweetCell: UICollectionViewCell,UICollectionViewDelegate,UICollectionViewDataSource {

...

【讨论】:

  • 您好,我不太明白,我已经通过 TweetCell 扩展实现了委托和数据源方法。
  • 你有没有在调试中看到当集合弹出时你有一些约束错误/冲突?
  • 不,没有任何约束错误/冲突。
  • 可能我明白了。在 prepareForReuse 单元格中使用重新加载集合数据是没有意义的。正如您一样,我将以“经典”方式重构代码,主要将集合代码与单元代码(和相关 xib)分开。所以调试起来更容易。
猜你喜欢
  • 1970-01-01
  • 2021-12-01
  • 1970-01-01
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-03
  • 1970-01-01
相关资源
最近更新 更多