ios - 如何使用 Swift 更新 UITableView?

标签 ios uitableview swift3

我正在尝试从 SQlite 数据库填充表格 View 。票证在控制台中打印出来,但 TableView 上什么也没有显示。更新和刷新的正确方法是什么?这是我的代码。谢谢!

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

最佳答案

动态 TableView 需要知道它们的委托(delegate)和数据源。如果您没有设置委托(delegate)和数据源,您可以在 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 {}
    }

关于ios - 如何使用 Swift 更新 UITableView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44285459/

相关文章:

iOS 开发为大屏幕做准备

iphone - 无法在 Interface Builder 中更改 UITableViewCell 大小

ios - 向 uitableviewcell 添加文本或绘图

ios - 录制视频并同时播放音频 ios

swift - 为什么在传递给具有可选类型的函数参数时强制使用 nil 的 uwrapped 类型不会崩溃?

ios - swift3 解析模型问题

ios - 在 Xcode 中使用 bash 的编译标志

ios - 在我的 UITableView 中,如何在选择时将 "selected cell color"重置为默认值?

ios - 当 for 循环从 NSArray 到达 NSNotFound 时如何中断

ios - UITableView 滚动时崩溃(iOS 7.1.2)