2014-11-19 21 views
7

Desidero ottenere il titolo dell'intestazione nella sezione di UITableView, per favore guidami qual è la sintassi in swift per ottenere il titolo dell'intestazione nella sezione.UITableView get titleForHeadersInSection swift

func tableView(tableView : UITableView, titleForHeaderInSection section: Int)->String 
{ 
    switch(section) 
    { 
    case 2:return "Title 2" 
     break 
    default :return "" 
     break 
    } 

} 

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

var title = tableView.titleForHeaderInSection[section]; 
if (title == "") { 
return 0.0; 
} 
return 20.0; 
} 

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

var title = tableView.titleForHeaderInSection[section] as String 
if (title == "") { 
return UIView(frame:CGRectZero); 
} 
var headerView:UIView! = UIView (frame:CGRectMake(0, 0, self.tableView.frame.size.width, 20.0)); 
headerView.backgroundColor = self.view.backgroundColor; 

return headerView; 
} 
+0

Perché non usi il numero di sezione per il confronto invece del titolo? – zisoft

+0

in realtà voglio conoscere la sintassi per ottenere il titolo Per intestazione nella sezione. –

risposta

3

Per chiamare questo metodo è necessario utilizzare il metodo di UITableViews titleForHeaderInSection. Questo metodo fornirà l'indice per la sezione corrente e ti verrà richiesto di restituire una stringa, la stringa restituita verrà impostata come intestazione.

Per beneficiare questo, lascia supporre che abbiamo un array di stringhe chiamato cars

cars = ["Muscle", "Sport", "Classic"] 

Possiamo quindi semplicemente chiamare

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? 
{ 
    // Ensure that this is a safe cast 
    if let carsArray = cars as? [String] 
    { 
     return carsArray[section] 
    } 

    // This should never happen, but is a fail safe 
    return "unknown" 
} 

Ciò restituirà titoli di sezione secondo l'ordine di cui sopra.

11

È possibile utilizzare il func già definito nella classe cioè:

self.tableView (tableView, titleForHeaderInSection: sezione)

Ad esempio, utilizzando il codice:

func tableView(tableView : UITableView, titleForHeaderInSection section: Int)->String { 
    switch(section) { 
    case 2:return "Title 2" 

    default :return "" 

    } 
} 

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

    var title = self.tableView(tableView, titleForHeaderInSection: section) 
    if (title == "") { 
     return 0.0 
    } 
    return 20.0 
} 
+0

Grazie. A proposito, non hai bisogno di "pausa". –

+1

Rimosso il 'break' - rimasto da un copia-incolla di uno snippet più grande :) – HungryArthur

Problemi correlati