繁体   English   中英

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

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

我正在使用Swift创建一个iOSPokémon数据库应用程序,用于我的A2计算课程。 在进行此项目之前,我没有使用过Swift,因此我在教自己使用相关示例,希望可以从中复制和粘贴。

我正在使用Xcode 6.1.1和Stephen CelisSQLite.swift库

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

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

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

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

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”数据,然后循环回到第一个并再次重复。 但仍然,tableview的标签文本没有更新。

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

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标识符对表名添加子脚本来创建嵌套的SQL标识符。 在这种情况下:

"Pokémon"."PokéName"

请参阅文档的“ 列名间隔”部分。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM