簡體   English   中英

如何使用Swift更新UITableView?

[英]How to Update UITableView With Swift?

我正在嘗試從SQlite數據庫填充表視圖。 票證已在控制台中打印出來,但是在表格視圖中什么也沒有顯示。 更新和刷新的正確方法是什么? 這是我的代碼。 謝謝!

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
    }     
}

動態表視圖需要知道其委托和數據源。 如果未設置委托和數據源,則可以在viewDidLoad函數中以編程方式添加它們。 像這樣:

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