首页 > 解决方案 > 如何根据一天中的时间自动滚动 UICollectionView 单元格

问题描述

我正在创建一个显示我所在城市的巴士时刻表的小型应用程序。我使用 UICollectionView 显示所有时间表:

从早上 06:00 到晚上 00:30。巴士每 30 分钟一班。

我希望我的单元格根据一天中的时间自动滚动,即使应用程序已关闭。我希望显示下一班车(例如下午 2:30)的单元格在下午 2:00 显示一个,并在下午 2:30 后自动滚动以显示下午 3:00 来的下一班车等...直到凌晨 00:30。在 00:30 之后,我想显示显示 06:00 的单元格。这个过程会无限地继续下去。

extension HomeViewController : UICollectionViewDelegate, UICollectionViewDataSource {
  
  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return busHoursList.count
  }
  
  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
    let busCell = collectionView.dequeueReusableCell(withReuseIdentifier: "busCellID", for: indexPath) as! BusCollectionViewCell
    busCell.layer.borderWidth = 0.6
    busCell.layer.cornerRadius = 15
    busCell.layer.borderColor = CGColor.init(red: 170/250, green: 170/250, blue: 170/250, alpha: 1)
    busCell.setupDepartureHours(withText: busDepartureHoursList[indexPath.row])
    
  }
}

标签: swiftxcodeuicollectionview

解决方案


1-我建议的解决方案是创建一个在打开应用程序时运行的函数,用它捕获当前时间,然后将集合的数据调整为当前时间。

2-之后,您可以运行异步函数以与当前时间同步并在应用程序运行时进行此更新考虑此代码库

 Timer.scheduledTimer(withTimeInterval: TimeInterval, repeats: true) { timer in
        ...
    }

推荐阅读