我想用来自 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/