I have a horizontal scrolling UICollectionView
with each collectionViewCell
containing a tableView
displaying a feed of post
objects. I would like to fetch data only once for each collectionViewCell
.
My current implementation fetches data whenever the collectionViewCell
is being dequeued, ie when the user swipes left and right on the collectionView
, the cell sometimes reloads and fetches data, interrupting the user experience.
到目前为止的代码:
//At ViewController
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! FeedCell
cell.topic = topics[indexPath.item]
return cell
}
//At FeedCell, the custom collectionViewCell
class FeedCell: UICollectionViewCell {
lazy var tableView: UITableView = {
let tv = UITableView(frame: .zero, style: .plain)
//Setup tableView work
return tv
}()
var topic: Topic? {
didSet {
if let _ = topic {
getData()
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
//Setup views work
}
这是我的一些其他尝试:
Attempt 1, move getData()
to init(frame: CGRect)
, but getData
doesn't get called as topic
isn't set yet.
Attempt 2, move getData()
to layoutSubviews()
like so:
override func layoutSubviews() {
if let _ = topic {
getData()
}
super.layoutSubviews()
}
But this recursively calls getData()
.