首页 > 解决方案 > 在 tableView 数据值 Swift 顶部添加或附加行的部分

问题描述

我已经创建了一个UITableView包含部分和行的 DataList。另外,我已经为函数实现了委托add & delete函数。实际上我需要添加或附加新的sectionrow选择的值。我的第一个模型是PickListDataItem->检索的其他部分值pickList

模型层次结构:PickListData-> let items: [Item]?-> var pickList: [SectionList]?->textField

我实现func didAddnewRow(_ sender: UIButton)了,但它在部分中添加了行,我需要在顶部添加新部分,名称为Selected.

附上我想要实现的当前和实际的图像。

标签: iosswiftuitableviewdelegates

解决方案


在向该部分添加行之前,您忘记添加新部分。插入“Selected”部分后,“A. Items”部分将下移。

func numberOfSections(in tableView: UITableView) -> Int {
        return AppData?.pickList?.count ?? 0
    }



 func sectionIndexTitles(for tableView: UITableView) -> [String]? {

  return [“Selected", “A. Items"]
}




 func didAddnewRow(_ sender: UIButton) {
    if let cell = sender.superview?.superview as? DictionaryTableViewCell,
        let indexPath = self.tableView.indexPath(for: cell) {

        if let selectedItem = AppData?.pickList?[indexPath.section].items?[indexPath.row] {

            let insertIndexPath = IndexPath(item: AppData?.pickList?[0].items?.count ?? 0, section: 0)


    if !AppData?.pickList.contains(where: {$0.title == “Selected" }) {


   AppData?.pickList.append(SectionList(title: “Selected”, items: selectedItem))

   tableView.insertSections(IndexSet([selectedItem]), with: .automatic)

    } else {

      AppData?.pickList?[0].items?.append(selectedItem)
  }


            cell.btnAdd.isHidden = true
            cell.btnDelete.isHidden = false
            tableView.beginUpdates()

            tableView.insertRows(at: [insertIndexPath], with: .automatic)
            tableView.endUpdates()

        }
    }
}

推荐阅读