滚动 UITableview 时自动滚动 UICollectionView

Mee*_*per 4 scrollview uitableview ios uicollectionview swift4.2

我有一个水平CollectionView的顶部和TableView下它,我想为我滚动TableViewCollectionView应该滚动动画与一些水平以及我与实现scrollItemTo,但CollectionView滚动慢,但我想它的工作,因为它工作在uberEats iOS应用在餐厅项目列表的详细信息同样在urbanClap应用程序中工作

这就像在表格视图部分标题到达顶部时逐个单元格移动视图单元格

PGD*_*Dev 8

您所指的 Uber Eats 优食应用功能的工作原理如下:每当 的特定部分tableView到达顶部时,collectionViewCell就会选择该特定部分。

从上面的陈述可以看出,

中的项目数collectionView= 中的部分数tableView

您可以通过跟踪 的顶部可见部分索引,tableView然后collectionViewCell在该特定索引处选择来实现此特定问题的解决方案,即

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView === self.tableView {
        if
            let topSectionIndex = self.tableView.indexPathsForVisibleRows?.map({ $0.section }).sorted().first,
            let selectedCollectionIndex = self.collectionView.indexPathsForSelectedItems?.first?.row,
            selectedCollectionIndex != topSectionIndex {
            let indexPath = IndexPath(item: topSectionIndex, section: 0)
            self.collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

collectionViewCell选择时更改颜色:

创建自定义UICollectionViewCell和覆盖**isSelected**属性来处理选中和未选中状态,即

class CollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var titleLabel: UILabel!

    override var isSelected: Bool {
        didSet {
            if self.isSelected {
                self.contentView.backgroundColor = #colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1)
            } else {
                self.contentView.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

backgroundColor在此之后,您无需手动更新其他地方的单元格。