从swift中获取plist的数组名称为tableview标签



这是我的plist文件

<plist version="1.0">
<dict>
<key>Complete</key>
<dict>  
    <key>Autonomic Nervous System</key>
    <array>
        <string>Cholinergic</string>
        <string>Anticholinergic</string>
    </array>
    <key>Peripheral Nervous System</key>
    <array>
        <string>Central relaxants </string>
        <string>Peripheral relaxants </string>
    </array>
</dict>
<key>Chap</key>
<array>
    <string>Autonomic Nervous System</string>
    <string>Peripheral Nervous System</string>
</array>
</dict>
</plist>

我只有在将其存储为字符串的" Chap"。

这是代码。

override func viewDidLoad() {
    super.viewDidLoad()
    let path = Bundle.main.path(forResource: "xml", ofType: "plist")
    let dict = NSDictionary(contentsOfFile: path!)
    chapters = dict!.object(forKey: "Chap") as! [String]
    ansTopics = dict!.object(forKey: "Complete") as! Array<String>
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return ansTopics.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "mainPage", for: indexPath)
    cell.textLabel?.text = ansTopics[indexPath.row]
    return cell
}

如何将数组名称作为字符串获取并将其传递给桌面元素?另外,如何为第二个表视图的相应章节索引主题(存储为字符串)?

当前,ansTopics返回信号SIGABERT错误。

问题是您的键Complete包含Dictionary而不是字符串的数组。因此,ansTopics应将其声明为[String: Any]

ansTopics = dict!.object(forKey: "Complete") as! [String: Any] //or Dictionary<String, Any>

如果您使用if letguard从字典中获取值而不是包裹的情况。

if let dict = NSDictionary(contentsOfFile: path!), let arrays = dict.object(forKey: "Complete") as? [String: Any] {
    ansTopics = arrays
}

edit:您需要声明字符串名称的类型数组chapter的一个实例属性,并使用字典的keys初始化它,然后随后将该数组与您的tableview一起使用。

var ansTopics = [String:Any]()
var chapters = [String]()

现在以这种方式初始化的章节。

if let dict = NSDictionary(contentsOfFile: path!), let arrays = dict.object(forKey: "Complete") as? [String: Any] {
    self.ansTopics = arrays
    self.chapters = self.ansTopics.keys.sorted()
}

相关内容

最新更新