簡體   English   中英

Swift:如何清除 collectionView 以便在 collectionViewCell 中重用

[英]Swift: How to clear collectionView for reuse in a collectionViewCell

我有一個collectionView,它位於collectionViewCell 內,並且在重用單元格時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硬編碼為隨機 integer,則mediaCollectionView會正確顯示單元格的數量。 但是,當動態設置為tweet?.mediaArray?.count時,單元格的數量不再正確。 我相信這是由於 collectionViewCell 的重用,因為當我滾動瀏覽 collectionView 時,這些單元格的計數開始跳躍。

如何正確重置 TweetCell 中的 collectionView?

更新:

嘗試2: -

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

上面的工作也不太順利。

嗯。 我認為您必須在單元內實現常規協議並重構所有代碼。

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

class TweetCell: UICollectionViewCell,UICollectionViewDelegate,UICollectionViewDataSource {

...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM