我有一个带有3个单元格的UICollectionViewController(HomeViewController
)
每个单元格都与屏幕尺寸一样大。
在最后一个单元格中,我有另一个UICollectionView(collectionView
)来显示数据
每次刷新时都应该刷新这些数据。
但这不起作用。
这是到目前为止的代码:
HomeViewController
class HomeViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let thirdCellId = "thirdCell"
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let thirdCell = collectionView.dequeueReusableCell(withReuseIdentifier: thirdCellId, for: indexPath) as! ThirdCell
thirdCell.refreshControl.addTarget(self, action: #selector(refreshData), for: UIControlEvents.valueChanged)
return thirdCell
}
@objc func refreshData(sender: UIRefreshControl) {
let cell = sender.superview as! ThirdCell <--- gives error: Could not cast value of type 'UICollectionView' to 'ExploreCell'
cell.loadData()
cell.refreshControl.endRefreshing()
print("Did work")
}
}
ThirdCell 代码:
class ThirdCell: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
override init(frame: CGRect) {
super .init(frame: frame)
setupCollectionView()
loadData()
setupRefreshControl()
}
// --- CollectionView ---
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.delegate = self
cv.dataSource = self
return cv
}()
func setupCollectionView() {
self.addSubview(collectionView)
// Setup constraints
}
// --- RefreshControl ---
var refreshControl: UIRefreshControl = {
let rfs = UIRefreshControl()
// Handle action in HomeViewController
return rfs
}()
func setupRefreshControl() {
if #available(iOS 10.0, *) {
collectionView.refreshControl = refreshControl
} else {
collectionView.addSubview(refreshControl)
}
refreshControl.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
refreshControl.bottomAnchor.constraint(equalTo: self.topAnchor, constant: 30).isActive = true
refreshControl.translatesAutoresizingMaskIntoConstraints = false
}
func loadData() {
// Load data
self.collectionView.reloadData()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}