Swift:如何使用SQLite列填充UITableView [英] Swift: how to populate UITableView with SQLite column

查看:113
本文介绍了Swift:如何使用SQLite列填充UITableView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to populate a basic UITableView (one-row cells) with a one-column coming from a SQLite database query.

我怎样才能在Swift?

How can I do that in Swift?

推荐答案

我使用 SQLite.Swift库!实际上非常简单。

I found the solution using the SQLite.Swift library! Very simple actually.

以下是城市sqlite数据库的示例,使用UITextField键入城市名称,使用UITableView显示匹配结果输入。

Here is an example with an sqlite database of cities, using a UITextField to type the name of the city, and a UITableView to display the matching results while typing.

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
    }     

}

这篇关于Swift:如何使用SQLite列填充UITableView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆