【发布时间】:2019-05-20 23:15:25
【问题描述】:
在tableView.reloadData() 之后可见的collectionView 立即意外显示第一行。
我正在构建一个tableView,其单元格中包含collectionView,用户可以在每个tableView 中滚动多个图像,就像Instagram 一样。我该如何解决?谢谢!
tableView 数据源
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return photoRolls.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath) as! HomeTableViewCell
if photoRolls.isEmpty {
return UITableViewCell()
}
let user: UserModel = users[indexPath.row]
let photoRoll: PhotoRoll = photoRolls[indexPath.row] //this Model contains post info: likes, comments etc.
let photoUrls: UrlStrings = urls[indexPath.row] //this Model contains a array of urlStrings for each collectionView inside the tableViewCell
cell.urlStrings = photoUrls
cell.photoRoll = photoRoll
cell.user = user
cell.delegate = self
return cell
}
tableViewCell 中的prepareForReuse 方法
override func prepareForReuse() {
super.prepareForReuse()
captionLabel.text = nil
profileImage.image = UIImage(named: "placeholderImg")
profileImageRight.image = UIImage(named: "placeholderImg")
collectionView.scrollToItem(at:IndexPath(item: 0, section: 0), at: .left, animated: false)//tried to remove this method, but the collectionView would not display the first row when it's visible
}
tableViewCell内collectionView的DataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return cellUrlArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeCollectionViewCell", for: indexPath) as! HomeCollectionViewCell
cell.url = cellUrlArray[indexPath.row]
return cell
}
就像问题标题所说的那样。我希望可见的collectionView 在tableView 在调用tableView.reloadData() 之后加载更多数据后保持在当前行上!再次感谢!
【问题讨论】:
-
只有一件题外话:您不必检查
photoRolls是否为空。如果为空,则没有单元格,因此不会调用cellForRowAt数据源方法 -
@RobertDresler 谢谢!
标签: ios swift uitableview collectionview