ios - 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
}
}
解决方案
在我看来,最简单的解决方案是在这行之后的sections 变量的开头插入一个新的Section。
sections = keys.map{ Section(letter: $0, name: groupedDictionary[$0]!.sorted()) }
就像是:
sections.insert(Section(letter: "Default", ["All makes"]), at: 0)
我可能会弄乱语法,因为我不知道你的Section
推荐阅读
- gradle - Gradle左移运算符(<<)与doLast行为差异
- python - 如何从密集层的所有预测输出中以最大概率获得输出?
- java - 转换日期中的“使用excel方法”数值 - java
- docker - 我在哪里可以找到 docker 的 nginx(稳定)?
- java - 如何测量 Spring Web 应用程序中的组件启动时间?
- spring - Spring项目依赖项不需要的默认行为而不被使用
- php - PHP POST 方法没有抛出或发送变量
- java - 如何保持两个 Youtube 视频同步?
- python - 我正在使用 audiodiff 来检测两个音频文件,无论它们是不同的还是相似的
- android - 使用 Room 加入查询