2015-01-22 26 views
12

Ho un elenco di nomi in ordine alfabetico, e ora voglio visualizzare questi nomi in una vista tabella. Sto lottando con il raggruppamento di questi nomi per ogni lettera.Sezioni alfabetiche nella vista tabella tabella in swift

Il mio codice è simile al seguente:

let sections:Array<AnyObject> = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] 
var usernames = [String]() 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ 

    let cellID = "cell" 

    let cell: UITableViewCell = self.tv.dequeueReusableCellWithIdentifier(cellID) as UITableViewCell 

    cell.textLabel?.text = usernames[indexPath.row] 

return cell 
} 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ 

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

    return 26 
} 


func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]!{ 

    return self.sections 
} 

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

     return index 
} 

func tableView(tableView: UITableView, 
    titleForHeaderInSection section: Int) -> String?{ 

     return self.sections[section] as? String 
} 

e tutto funziona abbastanza bene, tranne per il raggruppamento che rende la mia vista tabella finire così:

enter image description here

Quindi io ti conosco dovrebbe essere in grado di utilizzare la funzione filtrata in una matrice, ma non ho capito come implementarla.

Qualsiasi suggerimento su come procedere sarebbe apprezzato.

+1

'cell.textLabel? .text = username [indexPath.row]' è la vostra fonte di problema. Continui a compilare ogni sezione con gli stessi identici dati. –

+0

Sì, ho solo bisogno di filtrare correttamente l'array di nomi utente :) – martin

+0

mentre ci sono alcuni tentativi sotto - Ho trovato questo obiettivo-c più solido https://github.com/chrisladd/CGLAlphabetizer/blob/master/Example/CGLAlphabetizerDemo/ CGLContactsTableViewController.m – johndpope

risposta

1

Puoi mettere i tuoi array con i nomi nel dizionario con i tasti delle lettere.

Per esempio

var names = ["a": ["and", "array"], "b": ["bit", "boring"]]; // dictionary with arrays setted for letter keys 

allora avete bisogno di accedere ai valori nel vostro dizionario nel modo seguente

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ 
    return names[usernames[section]].count; // maybe here is needed to convert result of names[...] to NSArray before you can access count property 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ 

    let cellID = "cell" 

    let cell: UITableViewCell = self.tv.dequeueReusableCellWithIdentifier(cellID) as UITableViewCell 

    cell.textLabel?.text = names[usernames[indexPath.section]][indexPath.row]; // here you access elements in arrray which is stored in names dictionary for usernames[indexPath.section] key 

return cell 
} 
8

Questo è quanto ho recentemente implementato elenco ordinato in un tableView a Swift a livello di codice,

import UIKit 

class BreedController: UITableViewController{ 

    var breeds = ["A": ["Affenpoo", "Affenpug", "Affenshire", "Affenwich", "Afghan Collie", "Afghan Hound"], "B": ["Bagle Hound", "Boxer"]] 

    struct Objects { 
     var sectionName : String! 
     var sectionObjects : [String]! 
    } 

    var objectArray = [Objects]() 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     tableView.delegate = self 
     tableView.dataSource = self 
     tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "Cell") 
     // SORTING [SINCE A DICTIONARY IS AN UNSORTED LIST] 
     var sortedBreeds = sorted(breeds) { $0.0 < $1.0 } 
     for (key, value) in sortedBreeds { 
      println("\(key) -> \(value)") 
      objectArray.append(Objects(sectionName: key, sectionObjects: value)) 
     } 
    } 

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

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return objectArray[section].sectionObjects.count 
    } 

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell 
     // SETTING UP YOUR CELL 
     cell.textLabel?.text = objectArray[indexPath.section].sectionObjects[indexPath.row] 
     return cell 
    } 

    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
     return objectArray[section].sectionName 
    } 


} 
+0

mi ha aiutato molto bene. grazie per questo :) –

2

Scarica il file CountryList Json e inserisci il tuo progetto

https://gist.github.com/keeguon/2310008

var json = NSArray() 
    var arr_name = NSArray() 
    var arrIndexSection : NSArray = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] 


override func viewDidLoad() { 

    let path = Bundle.main.path(forResource: "countries", ofType: "json") 
    let data = NSData(contentsOfFile: path!) 
    json = (try! JSONSerialization.jsonObject(with: data as! Data, options: JSONSerialization.ReadingOptions.mutableContainers)) as! NSArray 
    arr_name = json.value(forKey: "name") as! NSArray; 

    tableview.reloadData() 
    super.viewDidLoad() 
} 
// Side List in tableview 
public func numberOfSections(in tableView: UITableView) -> Int { 
    return 26 
} 
public func sectionIndexTitles(for tableView: UITableView) -> [String]? { 
    return self.arrIndexSection as? [String] //Side Section title 
} 
public func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int 
{ 
    return index 
} 


public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
    return arrIndexSection.object(at: section) as? String 
} 


// number of rows in table view 
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
{ 
    let predicate = NSPredicate(format: "SELF beginswith[c] %@", arrIndexSection.object(at: section) as! CVarArg) 
    let arrContacts = (arr_name as NSArray).filtered(using: predicate) 
    return arrContacts.count; 

} 

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{ 
    let cell : TableViewCell=self.tableview.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell 
    let predicate = NSPredicate(format: "SELF beginswith[c] %@", arrIndexSection.object(at: indexPath.section) as! CVarArg) 
    let arrContacts = (arr_name as NSArray).filtered(using: predicate) as NSArray 
    cell.textLabel?.text = arrContacts.object(at: indexPath.row) as? String 
    return cell 
}