OGeek|极客世界-中国程序员成长平台

标题: ios - 当我滚动 UITableview 时自动滚动 UICollectionView [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 16:11
标题: ios - 当我滚动 UITableview 时自动滚动 UICollectionView

我在上面有一个水平的 CollectionView 和它下面的 TableView 我希望在滚动 TableView 时,我的 CollectionView 应该滚动和动画到我用 scrollItemToCollectionView 滚动到慢,但我希望它在 uberEats iOS 应用程序中的餐厅项目列表详细信息中工作,并且在 urbanClap 应用程序中工作

就像表格 View 部分标题到达顶部时逐个单元格移动 View 单元格一样



Best Answer-推荐答案


您所指的 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)
        }
    }
}

enter image description here

在选择时更改 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)
            }
        }
    }
}

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

关于ios - 当我滚动 UITableview 时自动滚动 UICollectionView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56072349/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4