我创建了一个包含 UITableView 的 UIViewController。 我希望它显示我在另一个位置创建的文件。
对应的类如下所示:
import UIKit
class BackupViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var rows:[String] = []
override func viewDidLoad() {
super.viewDidLoad()
self.table.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.table.dataSource = self
self.table.delegate = self
getFiles()
// Do any additional setup after loading the view.
}
func getFiles() {
let filemgr = FileManager.default
let path = filemgr.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).last
do {
rows = try filemgr.contentsOfDirectory(atPath: (path?.path)!)
// process files
} catch {
print("Error while enumerating files")
}
table.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rows.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = self.table.dequeueReusableCell(withIdentifier: "cell") as! UITableViewCell
cell.textLabel?.text = rows[indexPath.row]
return cell
}
@IBOutlet weak var table: UITableView!
}
它会正确读取文件
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int)
被调用(由于某种原因发生了 3 次),数组(目前)有 2 个元素。但是,该函数
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
从未被调用过,当然我得到了一张空 table 。
最佳答案
在 getFile() 函数中获取文件后,您需要重新加载 tableView。
func getFiles() {
let filemgr = FileManager.default
let path = filemgr.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).last
do {
rows = try filemgr.contentsOfDirectory(atPath: (path?.path)!)
self.table.reloadData()
// process files
} catch {
print("Error while enumerating files")
}
/*for file in files {
rows.append(file.absoluteString)
}*/
showFiles = true
}
一旦行中有一些值,您就需要调用 reloadData()。
关于swift - 表格单元格未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50488780/