我正在构建过滤器功能,您可以在其中选择所需的用户以查看其报告。本节几乎完成了,但是有一个错误,当我快速上下滚动时,某些选定的单元格被取消选择,而某些未选定的单元格被选中。
UserCell类包含一个UIView,一个UILabel和一个UISwitch。如何修复该错误,以便当我上下滚动时,单元格保持其选择?
编辑:
这是一些屏幕截图。第一个是当我切换5时,第二个是当我向下滚动时(底部的18不是bug)。
import UIKit
class BaseCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
func setupViews() {
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class UserCollectionView: BaseCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
let cellId = "userCellId"
var users = [User]()
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.backgroundColor = UIColor.white
cv.alwaysBounceVertical = true
cv.dataSource = self
cv.delegate = self
cv.translatesAutoresizingMaskIntoConstraints = false
return cv
}()
override func setupViews() {
super.setupViews()
users = UserDefaults.standard.getUsers() != nil ? UserDefaults.standard.getUsers()! : [User]()
self.addSubview(collectionView)
setupCollectionView()
}
func setupCollectionView() {
collectionView.register(UserCell.self, forCellWithReuseIdentifier: cellId)
collectionView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
collectionView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
collectionView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
collectionView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return users.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath as IndexPath) as! UserCell
cell.user = users[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: self.frame.width, height: 40)
}
}