简体   繁体   English

如何使用Swift更新UITableView?

[英]How to Update UITableView With Swift?

I'm trying to populate a table view from a SQlite database. 我正在尝试从SQlite数据库填充表视图。 Tickets get printed in the console, but nothings shows up on the table view. 票证已在控制台中打印出来,但是在表格视图中什么也没有显示。 What's the proper way to update and refresh? 更新和刷新的正确方法是什么? Here is my code. 这是我的代码。 Thanks! 谢谢!

import UIKit
import SQLite

class TicketTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var tickets = [String]()
    @IBOutlet weak var table: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let dm = DatabaseManager.shared
        let db = dm.db!
        do {
            for row in try db.prepare(dm.tickets) {
                let ticket = row[dm.pick]
                tickets.append(ticket)
                debugPrint(ticket)
            }
            table.reloadData()
        } catch {}
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tickets.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ticket")!
        cell.detailTextLabel!.text = tickets[indexPath.row]
        return cell
    }     
}

Dynamic table views needs to know their delegate and datasource. 动态表视图需要知道其委托和数据源。 If you didn't set the delegate and datasource, you can add them programmatically in your viewDidLoad function. 如果未设置委托和数据源,则可以在viewDidLoad函数中以编程方式添加它们。 Like this: 像这样:

override func viewDidLoad() {
        super.viewDidLoad()

        //Set delegate and datasource
        table.delegate = self
        table.dataSource = self

        let dm = DatabaseManager.shared
        let db = dm.db!
        do {
            for row in try db.prepare(dm.tickets) {
                let ticket = row[dm.pick]
                tickets.append(ticket)
                debugPrint(ticket)
            }
            table.reloadData()
        } catch {}
    }

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

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