在Swift中显示日历日期

时间:2017-11-01 16:02:07

标签: ios swift date calendar

我正在尝试为IOS制作每周日历。

It should look like this.

该示例的问题是代码是:使用 日期 数组

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

使用实际日期从01.01.2000 - 31.12.2099填充该数组,例如导致应用程序的性能非常糟糕。

有谁知道如何以更优雅的方式显示当前日期?

2 个答案:

答案 0 :(得分:0)

您可以使用以下扩展程序执行此操作:

见这里: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)

答案 1 :(得分:0)

这是使用Calendar enumerateDates的一个解决方案:

// 01.01.2000
let startComps = DateComponents(year: 2000, month: 1, day: 1)
let startDate = Calendar.current.date(from: startComps)!
// 31.12.2099
let endComps = DateComponents(year: 2099, month: 12, day: 31)
let endDate = Calendar.current.date(from: endComps)!

let components = DateComponents(hour: 0, minute: 0, second: 0) // midnight
var dates = [startDate]
Calendar.current.enumerateDates(startingAfter: startDate, matching: components, matchingPolicy: .nextTime) { (date, strict, stop) in
    if let date = date {
        if date <= endDate {
            dates.append(date)
        } else {
            stop = true
        }
    }
}