tableView未显示数组快速数据

问题描述 投票:0回答:2

我有一个tableView连接到阵列。数组不是空的,但tableView除了行以外什么都没有显示。您能帮我吗?

var invoicesDictionary = [String:[String]]()
var invoicesSectionTitles = [String]()
var invoices: [String] =  ["JV1", "R1", "JV2"]

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    for invoice in invoices {
        let invoiceKey = String(invoice.prefix(1))
        if var invoiceValues = self.invoicesDictionary[invoiceKey] {
            invoiceValues.append(invoice)
            self.invoicesDictionary[invoiceKey] = invoiceValues
        } else {
            self.invoicesDictionary[invoiceKey] = [invoice]
        }
    }

    invoicesSectionTitles = [String](invoicesDictionary.keys)
    invoicesSectionTitles = invoicesSectionTitles.sorted(by: { $0 < $1 })
    tableView.reloadData()

}

func numberOfSections(in tableView: UITableView) -> Int {
    return invoicesSectionTitles.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let invoiceKey = invoicesSectionTitles[section]
    if let invoiceValues = invoicesDictionary[invoiceKey] {
        return invoiceValues.count
    }
    return 0
}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let invoiceKey = invoicesSectionTitles[indexPath.section]

    if let invoiceValues = invoicesDictionary[invoiceKey] {
        cell.textLabel?.text = invoiceValues[indexPath.row]
    }

    return cell
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return invoicesSectionTitles[section]
}

func sectionIndexTitles(for tableView: UITableView) -> [String]? {
    return invoicesSectionTitles
}

我打印出了毫无疑问不是空的数组。我在另一个项目上尝试了此代码,它才起作用。

swift tableview
2个回答
0
投票

您必须将其放在viewDidLoad中:

tableView.delegate = self
tableView.dataSource = self

0
投票

您必须通过在viewDidLoad()内部传递以下行来告诉View控制器,它是表View功能的委托或已分配的VC

tableView.delegate = self
tableView.dataSource = self
© www.soinside.com 2019 - 2024. All rights reserved.