首页 > 解决方案 > UITableView 中其他单元格上方的自定义单元格

问题描述

我有一个 UITableView 从排序数组中获取数据。[AZ]。
我怎样才能像这样在顶部放置一个默认单元格来选择。

来自另一个应用程序的示例
如果用户不想单击任何其他单元格?
下面是我的 UITableViewCode。

   override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.delegate = self
        tableView.allowsSelection = true
        tableView.allowsMultipleSelection = false
        let groupedDictionary = Dictionary(grouping: nameArray, by: {String($0.prefix(1))})
        // get the keys and sort them
        let keys = groupedDictionary.keys.sorted()
        // map the sorted keys to a struct
        sections = keys.map{ Section(letter: $0, name: groupedDictionary[$0]!.sorted()) }
        self.tableView.reloadData()
    }
    // MARK: - Table view data source
    var selectedIndexPath = IndexPath()
    override func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections[section].names.count
        
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "HomeNames")
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeNames", for: indexPath)
        let section = sections[indexPath.section]
        if indexPath == selectedIndexPath {
            cell.accessoryType = UITableViewCell.AccessoryType.checkmark
        } else {
            cell.accessoryType = UITableViewCell.AccessoryType.none
        }
        cell.textLabel?.text = section.names[indexPath.row]
        return cell
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let section = sections[indexPath.section]
        selectedIndexPath = indexPath
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath as IndexPath)
        tableView.register(UINib(nibName: "BBcell", bundle: nil), forCellReuseIdentifier: "Cell")
        tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
        selectedHomeName = section.name[indexPath.row]
        navigationItem.title = (selectedHomeName)
        self.dismiss(animated: true, completion: nil)
    }
    override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return sections.map{$0.letter}
    }
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sections[section].letter
    }
}

标签: iosswiftuitableview

解决方案


在我看来,最简单的解决方案是在这行之后的sections 变量的开头插入一个新的Section。

sections = keys.map{ Section(letter: $0, name: groupedDictionary[$0]!.sorted()) }

就像是:

sections.insert(Section(letter: "Default", ["All makes"]), at: 0)

我可能会弄乱语法,因为我不知道你的Section


推荐阅读