2016-03-19 4 views
-1

В iOS/Swift я создал индексированный «клиентский» UITableView на основе свойства clientName в моем классе Client. Я создал словарь с А-Я в качестве разделов. Индексированный планшет отлично работает. Тем не менее, я пытаюсь выяснить способ определения, какая строка находится в исходном исходном массиве, когда пользователь выбирает строку. Я думал о том, чтобы создать какой-то массив перекрестных ссылок, за исключением того, что словарь заканчивается сортировкой для соответствия разделам, поэтому я не знаю, какой комбо соответствует класс/строка, исходный массив. Существует ли общий подход к решению этой проблемы?Хотите индексировать табличное представление со ссылкой на исходный массив

В попытке прояснить ...

class Client { 
    var clientId    : Int! 
    var firstName   : String! 
    var lastName    : String! 
    var email    : String! 
    var phone    : String! 
    ... 

    init() { 

    } 
} 

var clients: [Client] = [] 

// clients array loaded from web service 
... 

// Create dictionary to be source for indexed tableview 
func createClientDict() { 
    clientDict   = [String: [String]]() 
    clientSectionTitles = [String]() 

    var clientNames:[String] = [] 
    for i in 0..<clients.count { 
     let client = clients[i] 

     let clientName = "\(client.lastName), \(client.firstName)" 
     clientNames.append(clientName) 
    } 

    for name in clientNames { 
     var client: Client = Client() 

     // Get the first letter of the name and build the dictionary 
     let clientKey = name.substringToIndex(name.startIndex.advancedBy(1)) 
     if var clientValues = clientDict[clientKey] { 
      clientValues.append(name) 
      clientDict[clientKey] = clientValues 
     } else { 
      clientDict[clientKey] = [name] 
     } 
    } 

    // Get the section titles from the dictionary's keys and sort them in ascending order 
    clientSectionTitles = [String](clientDict.keys) 
    clientSectionTitles = clientSectionTitles.sort { $0 < $1 } 
} 

Теперь, когда пользователь вводит строку в Tableview, я могу получить раздел и строки (indexPath). Однако как определить, какая строка в массиве клиентов соответствует совпадению, если предположить, что могут быть дубликаты имен? Есть ли способ создать перекрестную ссылку индексированного раздела/строки, отображаемого в строке в исходном массиве «на лету»? Я собирался попытаться это сделать, создавая словарь, за исключением того, что словарь сортируется после, поэтому ничего не будет соответствовать. Может быть, я должен каким-то образом включить номер строки источника в/со словарем?

Вот код TableView:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! ClientCell 

    let clientKey = clientSectionTitles[indexPath.section] 
    if let clientValues = clientDict[clientKey] { 
     cell.clientName.text = clientValues[indexPath.row] 
    } 

    return cell 
} 

func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return clientSectionTitles.count 
} 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    let clientKey = clientSectionTitles[section] 
    if let clientValues = clientDict[clientKey] { 
     return clientValues.count 
    } 

    return 0 
} 

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
    return clientSectionTitles[section] 
} 

func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? { 
    return clientIndexTitles 
} 

func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int { 

    guard let index = clientSectionTitles.indexOf(title) else { 
     return -1 
    } 

    return index 
} 

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { 
    return 20 
} 

func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { 
    let headerView = view as! UITableViewHeaderFooterView 

    headerView.contentView.backgroundColor = UIColor (red: 0.0, green: 0.3294, blue: 0.6392, alpha: 1.0) 
    headerView.textLabel?.textColor = UIColor.greenColor() 
    headerView.textLabel?.font = UIFont(name: "Noteworthy-bold", size: 15.0) 
} 

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    selectedIndex = indexPath 

    // In the following prepare for segue, I need to somehow use the selected indexpath to find the correct entry 
    // in the clients array and pass it along. 

    performSegueWithIdentifier("clientDetailSegue", sender: self) 
} 
+0

Этот вопрос [нуждается в некоторой помощи] (http://importblogkit.com/2016/03/how-to-ask- а-хороший-стек переполнения-вопрос /). – nhgrif

+0

Где находится ваш код для просмотра таблицы? Также ... этот класс «Клиент» - это сбой, ожидающий своего появления ... '!' – nhgrif

+0

Я отредактировал, чтобы добавить код таблицы. Я пытался определить, что более страшно в моих определениях классов. Имея все свойства как необязательные, есть свои собственные проблемы, но, возможно, не так плохо. – Lastmboy

ответ

0

Я понял это. Я не понимал (пока недавно не пробовал), что вы можете вложить массив любого класса в словарь. Когда я сменил словарь на наличие в нем массива моих клиентов, все было решено. Я изменил свою функцию, как показано ниже.

func createClientDict() { 
    // Declared for view controller. Re-initialized here. 
    clientDict   = [String: [Client]]() 
    clientSectionTitles = [String]() 

    clients.sortInPlace ({ $0.lastName < $1.lastName }) 

    for c in clients { 
     let clientName = "\(c.lastName), \(c.firstName)" 

     // Get the first letter of the name and build the dictionary 
     let clientKey = clientName!.substringToIndex(clientName!.startIndex.advancedBy(1)) 
     if var clientValues = clientDict[clientKey] { 
      clientValues.append(c) 
      clientDict[clientKey] = clientValues 
     } else { 
      clientDict[clientKey] = [c] 
     } 
    } 

    // Get the section titles from the dictionary's keys and sort them in ascending order 
    clientSectionTitles = [String](clientDict.keys) 
    clientSectionTitles = clientSectionTitles.sort { $0 < $1 } 
} 

Однако эта линия была ключом к решению:

let clientDict = [String: [Client]]()