我真的很需要帮助,因为我是Swift的新手。我遇到的问题是找不到返回 numberOfRowsInSection
的方法场景:
我从 sectionArray 返回的表视图中有3个numberOfSections,如下所示:
{
"mbsdcie6_2_1": "Incomer 132 KV Parameters",
"mbsdcie6_2_2": [
3,
6,
4,
5,
8,
30,
31,
7,
18,
29,
1
]
},
{
"mbsdcie6_2_1": "SMS2 Parameters",
"mbsdcie6_2_2": [
9,
10,
11,
12,
13,
14
]
},
{
"mbsdcie6_2_1": "SMS 1 Parameters",
"mbsdcie6_2_2": [
15,
17
]
}
]
}
使用上面的数组,我可以像这样返回numberOfSections:
func numberOfSections(in tableView: UITableView) -> Int {
return self.sectionArray.count
}
但是,如何使用 sectionArray ??
返回 numberOfRowsInSection注意:
我想要 sectionArray
的“ mbsdcie6_2_2” 键中的 numberOfRowsfunc tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return "numberOfRows" // What to return here?
}
if section == 1 {
return "numberOfRows"
}
if section == 2 {
return "numberOfRows"
}
return 0
}
编辑1
这是我将数据添加到sectionArray的方式:
//它来自另一个Web服务,因此我将其添加到userdefaults中。
let headers = swiftyJSonVar [“ message”] [0] [“ mbsdcie6”] [“ mbsdcie6_2”]。arrayObject
kUserDefault.set(headers, forKey: kHeadersArray)
///在另一个ViewController中,我这样检索它:
var sectionArray = [Dictionary<String, Any>]()
override func viewWillAppear(_ animated: Bool) {
sectionArray = kUserDefault.array(forKey: kHeadersArray) as! [Dictionary<String, Any>]
print(sectionArray)
}
我知道这可能很愚蠢,这太简单了,但是由于我刚接触它,我莫名其妙地被困住了。 任何帮助将不胜感激,谢谢!
答案 0 :(得分:3)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if !sectionArray.isEmpty {
let sectionContent = sectionArray[section]["mbsdcie6_2_2"] as? [Int]
return sectionContent.count
} else {
return 0
}
}
答案 1 :(得分:2)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if sectionArray.indices.contains(section),
let sectionContent = sectionArray[section]["mbsdcie6_2_2"] as? [Int] {
return sectionContent.count
} else {
return 0
}
}
答案 2 :(得分:1)
尝试一下:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let singleSection = self.sectionArray[section]
if let rows = singleSection["mbsdcie6_2_2"] as? [Int] {
return rows.count
} else {
return 0
}
}