【发布时间】: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。