Reputation: 604
I have a UITableView that gets its data from a sorted array. [A-Z].
How can I place a default cell to select at the top like this.
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
}
}
Upvotes: 0
Views: 244
Reputation: 133
The simplest solution, in my opinion, would be to insert a new Section at the beginning of your sections variable after this line.
sections = keys.map{ Section(letter: $0, name: groupedDictionary[$0]!.sorted()) }
Something like:
sections.insert(Section(letter: "Default", ["All makes"]), at: 0)
I could have messed up the syntax a bit as I don't know your Section
Upvotes: 1