簡體   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