[英]Swift: How to make a new indexPath for the extra keys of a dictionary
我希望字典中的所有鍵都發生迭代,而不僅僅是 indexPath.row 中的一個
struct Whatever {
var title: String
var tag: [String:String?]?
}
var cases = [
Whatever(title: "Name1", tag: ["key1": "value1", "key2":"value2"]),
Whatever(title: "Name2", tag: ["key3": "value3"]
]
稍后在 ViewController 中:
let arrayCases = cases[indexPath.row]
let caseTag = arrayCases.tag!
for key in caseTag.keys {
cell.titleLabel?.text = key
//the magic stops somewhere here
}
for value in caseTag.values {
if value != nil {
cell.txt.text = value
} else {
cell.txt.text = arrayCases.title
}
}
你能告訴我如何為第二個標簽創建一個新的 indexPath.row 嗎? 好像它是“隨便”的單獨保險? 第二個問題 - 為什么每次構建不同的標簽后都會顯示 - 有時是“tag1”,有時是“tag2”? 謝謝!
如果使用標准表視圖(無段)在數據源中的每個項表示一行。 您不能簡單地創建一個新的 indexPath.row 。
您有兩個選擇:
使用部分:一個Whatever
是一個部分, title
是標題,每個tag
是一行(見下面的代碼)
連接標簽鍵和值
cell.titleLabel?.text = caseTag.keys.joined(separator: ", ") cell.txt.text = caseTag.values.joined(separator: ", ")
關於第二個問題:字典是無序的,沒有順序。 如果您需要特定訂單,請使用另一個 struct Tag
並將tags
數組,例如
struct Whatever {
let title: String
let tags: [Tag]
}
struct Tag {
let key, value : String
}
let cases = [
Whatever(title: "Name1", tags: [Tag(key: "key1", value: "value1"), Tag(key: "key2", value: "value2")]),
Whatever(title: "Name2", tags: [Tag(key: "key3", value: "value3"), Tag(key: "key4", value: "value4")])
]
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let case = cases[section]
return case.title
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
let section = cases[indexPath.section]
let case = section.tags[indexPath.row]
cell.titleLabel?.text = case.key
cell.txt.text = case.value
我將向您的結構添加兩個計算屬性,分別返回標簽鍵和值的列表,以使其余代碼更清晰。
var allTagKeys: String {
if let keys = tag?.keys {
return keys.sorted().joined(separator: ", ")
}
return ""
}
var allTagValues: String {
if let values = tag?.compactMap({ $0.value }) {
return values.joined(separator: ", ")
}
return ""
}
}
請注意,我向鍵添加了排序,不確定您是否需要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.