您所指的 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)
}
}
}
在选择时更改 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。