簡體   English   中英

如何使用與日期鍵匹配的字典填充表格視圖

[英]How to populate tableview with dictionary that matches the key for date

我知道標題令人困惑,但我有一本字典,其中包含日期(字符串)鍵和事件文本作為值。

如何首先確定哪些鍵與接下來 30 天內的日期匹配,然后使用這 30 天內的任何鍵/值對填充我的 tableview?

var calendarDataSource = [
    "08/12": "SomeData",
    "08/13": "SomeData",
    "08/14": "SomeData",
    "08/15": "SomeData",
    "08/16": "SomeData",
    "08/17": "SomeData",
    "08/18": "SomeData",
    "08/19": "SomeData",
    "08/20": "SomeData",
    "08/21": "SomeData",
    "08/22": "SomeData",
    "08/23": "SomeData",
    "08/24": "SomeData",
    "08/25": "SomeData"
]

您可以使用日歷獲取當前日期,以便從當前日期獲取當前月份和日期。

let date = Date()
let calendar = Calendar.current
var month = 0
var day = 0

一旦你有了它,我就創建了一個[String]()來保存與你的字典匹配的所有KEYS 然后,我創建了一個循環來計算第 1 天到第 30 天,並將每個日期添加到該數組中,以供您在字典中參考。 使用.date(byAdding:...)很重要,這樣您就可以計算可能有 28、30 或 31 天的月份。

var datesToPull = [String]()
for futureDay in 1...30{
    let toDate = Calendar.current.date(byAdding: .day, value: futureDay, to: date)
    month = calendar.component(.month, from: toDate!)
    day = calendar.component(.day, from: toDate!)

    // We have to format the days to a XX/XX value to handle your key requirements. 
    datesToPull.append("\(String(format: "%02d", month))/\(String(format: "%02d", day))")
}

如果您今天也想數數,只需將循環更改為此

for futureDay in 0...30{...

最后,要對這些鍵進行操作,請將其放在tableView(_ cellForRowAt:...)方法中或任何適合您需要的地方。

for key in calendarDataSource.keys{
    if datesToPull.contains(key){
        print("Date Found.")
    }
    else{
        print("No date found.")
    }
}

筆記

這不會保留任何排序。 由於使用字典,這無關緊要,但以防萬一你不知道。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM