아이템이 1개도 없을 때에는 No item!
이라고 쓰인 셀을 나타내야 한다. 대신 아이템이 하나라도 추가되면 이 셀은 사라진다
그리고 No item!
셀은 삭제나 이동이 불가능해야 한다
class ItemsViewController: UITableViewController {
var itemStore: ItemStore!
@IBAction func addNewItem(_ sender: UIButton) {
let newItem = itemStore.createItem()
if let index = itemStore.allItems.firstIndex(of: newItem) {
let indexPath = IndexPath(row: index, section: 0)
if itemStore.allItems.count == 1 {
replaceNoItemCellWithItemCell(at: indexPath)
} else {
tableView.insertRows(at: [indexPath], with: .automatic)
}
}
}
func replaceNoItemCellWithItemCell(at: indexPath) {
let cell = tableView.cellForRow(at: indexPath)
let item = itemStore.allItems[indexPath.row]
cell.textLabel?.text = item.name
cell.detailTextLabel?.text = "$\(item.valueInDollars)"
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
itemStore.allItems.isEmpty ? 1 : itemStore.allItems.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
if !itemStore.allItems.isEmpty {
let item = itemStore.allItems[indexPath.row]
cell.textLabel?.text = item.name
cell.detailTextLabel?.text = "$\(item.valueInDollars)"
} else {
cell.textLabel?.text = "No item!"
cell.detailTextLabel?.text = nil
}
return cell
}
위에서처럼 하니까 작동은 잘 하는데 개인적으로 no item cell -> item cell 로 바뀔 때 애니메이션 효과가 없는 게 아쉬웠다...그래서 공식문서를 뒤지다가 특정 위치의 cell 을 애니메이션 효과를 곁들여서 다시 로드해준다는 reloadRows(at:with:) 메서드를 발견했다.
작동 방식이 어떻게 되는 지 몰라서 삽질을 좀 하다가 insertRows(at:with:) 메서드와 마찬가지로 tableView 에서 해당 메서드를 호출하면 델리게이트의 tableView(_:cellForRowAt:) 메서드가 호출되는데, 이제 얘는 해당 위치에 새로 추가가 아니라 새로운 셀로 바꿔주는 것임을 깨달았다! 그래서 아이템 개수가 하나인 경우 교체 작업을 수행하도록 reloadRows(at:with:) 를 호출했더니 애니메이션 효과까지 잘 적용되면서 대체됐다!
원래는 replaceNoItemCellWithItemCell(at: indexPath) 에다가 아이템 개수가 여러개였다가 다 삭제되어서 다시 no item cell 이 되는 경우를 위한 replaceItemCellWithNoItemCell(at: indexPath) 까지 두 개의 커스텀 메서드가 있었는데 reloadRows(at:with:) 을 사용하면서 둘 다 삭제할 수 있었다.
@IBAction func addNewItem(_ sender: UIButton) {
let newItem = itemStore.createItem()
if let index = itemStore.allItems.firstIndex(of: newItem) {
let indexPath = IndexPath(row: index, section: 0)
if itemStore.allItems.count == 1 {
tableView.reloadRows(at: [indexPath], with: .automatic) // 여기요 여기
} else {
tableView.insertRows(at: [indexPath], with: .automatic)
}
}
}
class ItemsViewController: UITableViewController {
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
itemStore.allItems.isEmpty ? false : true
}
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
itemStore.allItems.isEmpty ? false : true
}
}