swift - 表格单元格未被调用

标签 swift uitableview

我创建了一个包含 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/

相关文章:

xcode - 如何初始化相互依赖的属性

ios - 方法无效 - 自定义单元格

iphone - 我的 UITableView cellForRowAt Index for Single Selection 有什么问题?

ios - 在 View 之间切换后,Swift Timer() 不会更新标签

swift - 条件绑定(bind)的初始化程序必须具有可选类型,而不是 'AVAudioInputNode'//Swift 4.2

ios - 在 TableView Controller 中显示 nil 的原型(prototype)单元标签

ios - 从解析中检索用户数据以快速显示在 TableView 中

iphone - 不会调用 canMoveRowAtIndexPath - 但会调用 canEditRowAtIndexPath

ios UITableview 单个单元格上的多个选择选项?

ios - Swift - 对于 iOS 7/iOS 8 及更高版本同时使用 UIAlertController 和 UIAlertView