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

标签 ios swift swift3 plist

这是我的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
}

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

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

最佳答案

问题是您的键 Complete 包含 Dictionary 而不是字符串数组。所以 ansTopics 应该声明为 [String: Any]

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

如果你使用 if letguard 从 Dictionary 中获取值而不是强制包装它,那就更好了。

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

编辑:您需要声明一个字符串名称chapter类型数组的实例属性,并用字典的keys初始化,以后使用该数组与您的表格 View 。

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()
}

关于ios - 从 plist 中获取数组名称作为 swift 中的 tableview 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41372996/

相关文章:

ios - 为什么 iOS 上的后台录音不起作用?

ios - uitableview insertRowAtIndexPath 将行加倍

ios - 如何在 iOS Swift 中导入 opencv2 框架

Swift 3 升级 : Type 'Dictionary<NSObject, AnyObject>?' has no subscript members

swift - 在 Swift Linux 中展开长数据类型

ios - 显示/关闭演练 - iOS 应用程序结构

ios - ARKit – 沿特定轴拖动节点(不是在平面上)

swift - 当 App 显示 NSAlert 时保持 Cocoa 窗口最小化

ios - 如何使类快速符合协议(protocol)?

ios - swift 3 : nil when trying to get email from Twitter using Fabric