我有变量 startTime 和 endTime 。在 collectionCell 我需要显示开始时间和结束时间,但我需要在开始时间之间结束时间仍然是时间范围。
例如:
这一天有24小时。我的 startTime是06:00 ,我的结束时间是13:00。 我需要在 06:00 到 13:00 和 collectionCell 中显示范围我想看到它:
06:00
07:00
08:00
09:00
10:00
11:00 <关于/强>
12:00
13:00
我可以显示吗?怎么做?
我的代码:
var startTime: String = "06:00"
var endTime: String = "13:00"
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return // what need is there to write?
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "timeCell", for: indexPath) as! BookingTimeCell
cell.timeLabel.text = // what need is there to write?
return cell
}
答案 0 :(得分:0)
经常编程是将大问题分解成小块。以下是您面临的问题:
String
。您不能在字符串中添加一小时。需要将其转换为Date
startTime
和endTime
之间生成一个小时数组,并在startTime
或endTime
更改时更新此数组。这是一种方法:
class ViewController: UIViewController, UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
var startTime: String = "06:00"
var endTime: String = "13:00"
var timeRange = [String]() // this array contains all the hours between your startTime and endTime
// The formatter is responsible for converting a String to a Date and vice-versa
var timeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
return formatter
}()
override func viewDidLoad() {
super.viewDidLoad()
// Every time startTime and endTime change, reload the collection view
// with a code block like this
if let timeRange = generateTimeRange() {
self.timeRange = timeRange
self.collectionView.reloadData()
} else {
// Handle error
}
self.collectionView.dataSource = self
}
// Call this function in viewDidLoad and whenever startTime or endTime change
// Note this function returns an empty array if the time range crosses the day
// boundary, for example: startTime = 22:00, endTime = 02:00
func generateTimeRange() -> [String]? {
var result = [String]()
guard var startDate = timeFormatter.date(from: startTime) else { return nil }
guard let endDate = timeFormatter.date(from: endTime) else { return nil }
while startDate <= endDate {
result.append(timeFormatter.string(from: startDate))
startDate = Calendar.current.date(byAdding: .hour, value: 1, to: startDate)!
}
return result
}
// MARK: - UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return timeRange.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "timeCell", for: indexPath) as! BookingTimeCell
cell.timeLabel.text = timeRange[indexPath.row]
return cell
}
}
结果: