【问题标题】:Not able to pass array name into table view in Swift 3无法将数组名称传递到 Swift 3 中的表视图中
【发布时间】:2016-12-29 06:29:09
【问题描述】:

我对 swift 代码比较陌生。无法将 plist 中的数组文本传递到表格视图中...

现在我在模拟器中得到一个空表视图

override func viewDidLoad() {
    super.viewDidLoad()

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

}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return chapters.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "mainPage", for: indexPath)
    cell.textLabel?.text = chapters[indexPath.row]
    return cell
}

这是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>

【问题讨论】:

  • self.chapters 的输出是什么?
  • 尝试在self.chapters = self.ansTopics.keys.sorted()self.tableView.reloadData() 之后重新加载tableview 一次
  • @NiravD 空模拟器
  • @Mr.Bista 空输出
  • @Nish Dictionary 没有任何顺序,因此无法按照 plist 文件中可用的顺序显示数据。

标签: ios arrays swift swift3 plist


【解决方案1】:

试试这个代码,它可能对你有帮助

let arrays = dict.object(forKey: "Complete") as? Dictionary<String,AnyObject>

代替

let arrays = dict.object(forKey: "Complete") as? [String: Any]

谢谢

【讨论】:

  • 错误:无法推断泛型参数“key”强制转换为“Dictionary<__>”
  • 作为?字典
  • 现在 self.ansTopics = arrays 行抛出错误的执行错误
  • 因为 ansTopic 是数组,你从我的代码中获取字典,所以将其类型更改为数组中的字典
  • 这一行使章节名称按字母顺序显示... self.chapters = self.ansTopics.keys.sorted() 可以采取什么措施来避免它并按照我的偏好顺序放置它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-06
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多