In cellForRowAt, how can you ensure that only elements with the same 1st letter as the section title get included?

50 Views Asked by At

What happens right now:

numberOfRowsInSection correctly gets the number of rows in each section by using a dictionary of words with same starting letter as section heading. So Australia and Argentina go in section A.

Problem is that didSelectRowAt can't use that same dictionary to set the cell because well it needs to select a different part of the struct (so didSelect and the precursors of the dictionary are in the same struct)

So in cellForRowAt, I match it to didSelectRowAt, so that the didSelectRowAt works perfectly. Problem then is for each section, all alphabet elements are included, not only the ones with the same 1st letter as the section title.

So for A, it would include something like Australia, Argentina. For B it would include Australia, Argentina, Brazil. For C Australia, Argentina, Brazil, Canada. Instead it should only include Canada at C etc

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     var cell = UITableViewCell()
    let aveKey = sectionTitle[indexPath.section]
    if let aveValue = aveDict[aveKey] {
        cell.textLabel?.text = dropDownOptions[indexPath.row]
    }
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  self.delegate.dropDownPressed(string: dropDownOptions1[indexPath.row])
    print(dropDownOptions[indexPath.row])
    self.tableView.deselectRow(at: indexPath, animated: true)
}


 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return aveDict[sectionTitle[section]]?.count ?? 0


}

Part B: The structure

   struct CountryCodeItem {
let prefix: String
let country: String
let dashy: String
var displayText: String {
    "\(prefix) \(country)"
}
}
    //in viewDidLoad
    
    button.dropView.dropDownOptions = countryCodes.map { $0.displayText }
    button.dropView.dropDownOptions1 = countryCodes.map { $0.prefix }
    button.dropView.dropDownOptions2 = countryCodes.map { $0.country}

Part C: The dictionary

func createAvengersDict() {
    for avenger in dropDownOptions2 {
        let firstLetterIndex = avenger.index(avenger.startIndex, offsetBy: 1)
        let avengerKey = String(avenger[..<firstLetterIndex])
        if var avengerValues = avengersDict[avengerKey] {
            avengerValues.append(avenger)
            avengersDict[avengerKey] = avengerValues
        } else {
            avengersDict[avengerKey] = [avenger]
        }                                      
    }
    avengerSectionTitles = [String](avengersDict.keys)
    
    avengerSectionTitles = avengerSectionTitles.sorted(by: { $0 < $1
    })
}
0

There are 0 best solutions below