我正在尝试为 IOS 构建每周日历。
该示例代码的问题是:使用日期数组
let dates = ["7/10/2017", "7/11/2017", "7/12/2017", "7/13/2017", "7/14/2017", "7/15/2017", "7/16/2017"]
func spreadsheetView(_ spreadsheetView: SpreadsheetView, cellForItemAt indexPath: IndexPath) -> Cell? {
if case (1...(dates.count + 1), 0) = (indexPath.column, indexPath.row) {
let cell = spreadsheetView.dequeueReusableCell(withReuseIdentifier: String(describing: DateCell.self), for: indexPath) as! DateCell
cell.label.text = dates[indexPath.column - 1]
return cell
用 2000 年 1 月 1 日到 2099 年 12 月 31 日的实际日期填充该数组,例如导致应用程序的性能非常糟糕。
有人知道如何以更优雅的方式显示当前日期吗?
最佳答案
您可以使用以下扩展来实现此目的:
请参阅此处:Swift: Print all dates between two NSDate()
extension Date{
func generateDatesArrayBetweenTwoDates(startDate: Date , endDate:Date) ->[Date]
{
var datesArray: [Date] = [Date]()
var startDate = startDate
let calendar = Calendar.current
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd"
while startDate <= endDate {
datesArray.append(startDate)
startDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
}
return datesArray
}
}
用法:
let dates = Date().generateDatesArrayBetweenTwoDates(startDate: Your Start Date Object , endDate: Your End Date Object)
关于ios - 在 Swift 中显示日历日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47058959/