I have some data which is pulled from a DB and stored in an array within my UITableViewController
. However, when I try to put the data inside each of my cells, I get an error that my index is out of the bounds of the array.
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
}
}
Here is the cellItems
variable and also where it is populated:
var cellItems: NSArray = NSArray() {
didSet {
tableView.reloadData()
}
}
func itemsDownloaded(items: NSArray) {
cellItems = items
tableView.reloadData()
}
Here is the static table view in the storyboard:
What I want to do, which I've took out of the code for as it still fails before reaching this part, is to use the 'item' variable I declare inside cellForRowAt
and populate each of my cell outlets with a part of the object,
ie: descCell.descLabel.text = item.name
The error I get is:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
on the line
let descCell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)!
You should not use a table view controller with static cells and cellForRowAt
at the same time. You should use dynamic prototypes to populate an array dynamically.
To change the content type of your table view, select it in Interface Bulder, open the Attributes inspector (the fourth icon from the left in the right sidebar) and select Dyanmic Prototypes for Content under the Table View section.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.