Thanks - I made that work…
@IBAction func addNewItem(_ sender: UIButton) {
// Listing 9.15 p 205
// Make a new index path for the 0th section, last row
/* this crashes the app
let lastRow = tableView.numberOfRows(inSection: 0)
let indexPath = IndexPath(row: lastRow, section: 0)
*/
// Create a new item and add it to the store
let newItem = itemStore.createItem()
/* print("Number of sections: \(tableView.numberOfSections)")
for i in 0..<sections.count {
print("Section \(i): \(sections[i])")
}*/
// Silver challenge - can I use this to designate my 'No Items!' row?
// let placeholderIndex = tableView.indexPathsForVisibleRows!
// Figure out where that item is in the array
if let index = itemStore.over50Items.firstIndex(of: newItem) {
// Silver challenge - trying to delete placeholder row before adding the first item from over50Items
let indexPath = IndexPath(row: index, section: 0)
// Insert this new row into the table
tableView.insertRows(at: [indexPath], with: .automatic)
tableView.footerView(forSection: 0)?.isHidden = true // footer goes away
print("Item Name: \(newItem.name)")
print("Value: $\(newItem.valueInDollars)")
// print("Section: \(newItem.overUnder50)")
} else if let index = itemStore.under50Items.firstIndex(of: newItem) {
// Silver challenge - trying to delete placeholder row before adding the first item from over50Items
let indexPath = IndexPath(row: index, section: 1)
tableView.insertRows(at: [indexPath], with: .automatic)
tableView.footerView(forSection: 1)?.isHidden = true // footer goes away
// console stuff
print("Item Name: \(newItem.name)")
print("Value: $\(newItem.valueInDollars)")
}
}
// Listing 9.20 p 208 - Implementing table view row deletion
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
// If the table view is asking to commit a delete command...
if editingStyle == .delete {
// Silver challenge: apply remove/delete only when the itemList has items
if indexPath.section == 0 {
// remove the item from the store
itemStore.removeItem(itemStore.over50Items[indexPath.row])
// Also remove that row from the table view with an animation
tableView.deleteRows(at: [indexPath], with: .automatic)
if itemStore.over50Items.isEmpty {
tableView.footerView(forSection: 0)?.isHidden = false
// footer re-appears
}
} else {
itemStore.removeItem(itemStore.under50Items[indexPath.row])
// Also remove that row from the table view with an animation
tableView.deleteRows(at: [indexPath], with: .automatic)
if itemStore.under50Items.isEmpty {
tableView.footerView(forSection: 1)?.isHidden = false
// footer re-appears
}
}
}
}
// Create a standard footer that includes the returned text.
override func tableView(_ tableView: UITableView, titleForFooterInSection
section: Int) -> String? {
return "No Items!"
}