Xcode 8.2.1 / Swift 3 - Load TableView from Plist Array of Dictionaries

后端 未结 1 1433
无人共我
无人共我 2021-01-14 10:25

I have a plist that I copied into my project to use it in a TableView. The plist loads and I verified by printing the contents and number of rows to the console. When I bu

相关标签:
1条回答
  • 2021-01-14 11:08

    Looks like you need to set your tableView delegate and datasource. Add the following lines to your viewDidLoad.

        self.tableView.delegate = self
        self.tableView.dataSource = self
    

    You also want to move your numberOfRowsInSection and cellForRowAt functions out of viewDidLoad and add the word override in front of them.

    Full code:

    import UIKit
    
    class TableViewController: UITableViewController {
    
        var filePath: String?
        var employees: [[String: String]] = []
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            self.tableView.delegate = self
            self.tableView.dataSource = self
    
            filePath = Bundle.main.path(forResource: "directory", ofType: "plist")
            employees = NSArray(contentsOfFile: filePath!) as! [[String: String]]
    
            for item in employees {
    
                print(item["Name"] as Any)
                print(item.count)
                print(employees.count)
            }
        }
    
        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return (employees.count)
        }
    
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewControllerTableViewCell
            cell.nameLabel.text = (employees[indexPath.row]["Name"]) //as! String)
            cell.positionLabel.text = (employees[indexPath.row]["Position"]) //as! String)
    
            return cell
        }
    }
    
    0 讨论(0)
提交回复
热议问题