如何将 UITableView 的单元格文本设置为 Swift 中的数据库单元格内容?

How can I set a UITableView's cell text to database cell's content in Swift?

我正在使用 Swift 创建一个 iOS Pokémon 数据库应用程序,用于我的 A2 计算课程作业。在这个项目之前,我没有使用过 Swift,所以我正在使用相关示例自学,希望可以从中复制粘贴。

我正在使用 Xcode 6.1.1 和 SQLite.swift library from Stephen Celis

一个这样的测试是生成一个 UITableView,它可以从我预先存在的、预先填充的数据库中读取。

我已经设法让 UITableView 创建所有单元格 - 并将 detailTextLabel 设置为 indexPath(加 1,因此它从 1 开始到 721 结束,而不是从 0 开始到 720 结束)。所以我在 table 中有 721 个单元格就好了。

但是,我似乎无法让每个单元格的 textLabel 显示正确的数据。相反,它会为每个单元格显示 "SQLite.Expression"。

在ViewController.swift文件的ViewControllerclass上方,我有

let db = Database("/Users/rhysmorgan/Documents/Coding/DatabaseLoadTest/Pokémon Database.sqlite", readonly: true)
let pokemonTable = db["Pokémon"]
let name = Expression<String>("PokéName")
let gen = Expression<Int>("Generation")

在主要的 tableView 函数中,我有

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cellIdentifier = "Cell"
    let rowno: Int = indexPath.row + 1
    let formatter = NSNumberFormatter(); formatter.minimumIntegerDigits = 3
    let formattedrowno = formatter.stringFromNumber(rowno)
    let pokemonname = pokemonTable[name]


    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as UITableViewCell

        cell.textLabel?.text = "\(pokemonname)"
        cell.detailTextLabel?.text = "\(formattedrowno!)"

    return cell
}

有人能帮助我吗? 提前致谢!

编辑:我设法通过包装

让它从第一行开始显示正确的值
cell.textLabel?.text = "\(pokemonname)"
cell.detailTextLabel?.text = "\(formattedrowno!)"

在一个

for pokemon in pokemonTable {
/*insert above lines*/
}

循环并添加

println(pokemon[name])

生成每条记录,打印其 "PokéName" 列数据。然后它又重复了 13 次。所以它将第一条记录的 "PokéName" 列数据打印到第 721 列的 "PokéName" 数据,循环回到第一个并再次重复此操作。但是,table视图的标签文本仍然没有更新。

正如您在编辑中发现的那样,必须执行查询才能访问基础数据,这发生在您 运行 forin 循环时。您可以将数据存储在内存中,而不是调用 forin例如:

let data = Array(pokemonTable)
let cellIdentifier = "Cell"
lazy var formatter: NSNumberFormatter = {
    let formatter = NSNumberFormatter()
    formatter.minimumIntegerDigits = 3
    return formatter
}()

func tableView(
    tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath
) -> UITableViewCell {
    let idx = indexPath.row
    let rowNo = formatter.stringFromNumber(idx + 1)
    let pokemonName = data[idx][name]

    let cell = tableView.dequeueReusableCellWithIdentifier(
        cellIdentifier, forIndexPath: indexPath
    ) as UITableViewCell

    cell.textLabel?.text = pokemonName
    cell.detailTextLabel?.text = rowNo

    return cell
}

在这种情况下,我们执行一次 SQL 查询,将所有行存储在 data 数组中(见第一行),然后在 tableView:cellForRowAtIndexPath:方法。


在你编辑之前,为了完整起见,请看一下这一行:

let pokemonname = pokemonTable[name]

这是通过使用您之前定义的 SQL 标识符为 table 名称添加子脚本来创建嵌套的 SQL 标识符。在这种情况下:

"Pokémon"."PokéName"

请参阅文档的 Column Namespacing 部分。