ios - Swift:如何使用 SQLite 列填充 UITableView

标签 ios swift sqlite uitableview

我想用来自 SQLite 数据库查询的单列填充基本的 UITableView(单行单元格)。

我如何在 Swift 中做到这一点?

最佳答案

我使用 SQLite.Swift library 找到了解决方案!其实很简单。

这是一个带有城市 sqlite 数据库的示例,使用 UITextField 键入城市名称,并使用 UITableView 在键入时显示匹配结果。

import UIKit
import SQLite

let path = NSBundle.mainBundle().pathForResource("cities", ofType: "sqlite")! // in case of a sqlite file called 'cities.sqlite'
// N.B. the sqlite file needs to be added to the project and to the application target

let db = Database(path, readonly: true)

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var cities : [String]?

    @IBOutlet weak var searchTextField: UITextField!
    @IBOutlet var resultsTableView : UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        searchTextField.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
    }

    func textFieldDidChange(textField: UITextField) {
        cities = [String]()
        for row in db.prepare("SELECT name FROM cities WHERE name LIKE \"%"+textField.text+"%\" LIMIT 30") {
            cities!.append(row[0] as! String)
        }
        resultsTableView!.reloadData()
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if cities == nil {
            return 0
        }
        return cities!.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("CityCell") as! UITableViewCell
        cell.textLabel?.text = self.cities?[indexPath.row]
        return cell
    }     

}

关于ios - Swift:如何使用 SQLite 列填充 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32232081/

相关文章:

jquery - Ajax 调用在 ios 中立即失败,文本状态为 : error and HTTP status 0 on Cordova,

swift - 使用 Swift 将文本添加到 CGContext

ios - Swift Parse - 使用 PFQuery 或 QueryWithSubqueries 函数

ios - Xcode UI 测试 UIKeyInput typeText

c# - Sqlite 数据库给我警告

java - 并发是在sqlite中自动处理的吗?

ios - 使用 iMovie 创建 iOS 应用程序预览

ios - 如何从表格单元格中删除 UIGestureRecognizer

安卓 SQLite : SQLiteException: near "?" syntax error

ios - 使用 Swift 调用电话号码