繁体   English   中英

用数组中的数据实现静态表视图单元

[英]Implementing static table view cells with data in an array

我有一些数据从数据库中提取并存储在UITableViewController的数组中。 但是,当我尝试将数据放入每个单元格中时,出现一个错误,我的索引超出了数组的范围。

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

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

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let item: ItemPreBasketModel = cellItems[indexPath.row] as! ItemPreBasketModel
    if indexPath.row == 0 {
        //Desc cell
        let cellIdentifier: String = "descCell"
        let descCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
        return descCell
    } else if indexPath.row == 1 {
        //Price cell
        let cellIdentifier: String = "priceCell"
        let priceCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
        return priceCell
    } else if indexPath.row == 2 {
        //Quantity cell
        let cellIdentifier: String = "quantityCell"
        let quantityCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
        return quantityCell
    } else {
        //Submit cell
        let cellIdentifier: String = "submitCell"
        let submitCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
        return submitCell
    }
}

这是cellItems变量,也是它的填充位置:

var cellItems: NSArray = NSArray() {
    didSet {
        tableView.reloadData()
    }
}

    func itemsDownloaded(items: NSArray) {
    cellItems = items
    tableView.reloadData()
}

这是情节提要中的静态表格视图:

表格视图的设置

我想要做的是使用代码,因为它在到达这一部分之前仍然失败,因此我从代码中删除了它,它是使用在cellForRowAt内部声明的“ item”变量,并用对象的一部分填充每个单元格出口,

即: descCell.descLabel.text = item.name

我得到的错误是:

线程1:致命错误:展开一个可选值时意外地找到零

在线上

let descCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!

您不应将表视图控制器与静态单元格和cellForRowAt同时使用。 您应该使用动态原型动态填充数组。

要更改表格视图的内容类型,请在Interface Bulder中将其选中,打开“属性”检查器 (右侧栏中左侧第四个图标),然后在“ 表格视图”部分下选择“ 内容的动态 原型 ”。

属性检查器中的“动态原型”设置

暂无
暂无

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

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