【发布时间】:2015-08-28 04:14:57
【问题描述】:
我想用来自 SQLite 数据库查询的一列填充基本 UITableView(单行单元格)。
如何在 Swift 中做到这一点?
【问题讨论】:
标签: ios swift sqlite uitableview
我想用来自 SQLite 数据库查询的一列填充基本 UITableView(单行单元格)。
如何在 Swift 中做到这一点?
【问题讨论】:
标签: ios swift sqlite uitableview
我使用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
}
}
【讨论】: