2011-11-10 15 views
47

HO LETTO la documentazione Apple e non è comprensibile per un principiante in Objective-C come me. Sto cercando di implementare la multicanalità UITableView seguendo questo esempio link e semplicemente non funziona, quindi ho bisogno di capire come funziona cellForRowAtIndexPath, perché per me personalmente questo metodo sembra piuttosto complicato.Come funziona cellForRowAtIndexPath?

1) Che cosa restituisce? UITableViewCell? Ma perché sembra così strano?

-(UITableViewCell *)tableView:(UITableView *)tableView 
  • Che cosa è questo? Potresti spiegare per favore?

2) Come viene chiamato e cosa è più importante come posso collegarlo a un certo UITableView ??? Cosa succede se ho due e secondTableViewUITableView e voglio che siano diversi (per eseguire cellForRowAtIndexPath in modo diverso)? Come faccio a collegare il mio UITableViews a questo

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 

il metodo accetta NSIndexPath, non UITableView. Cosa sto per fare?

+0

Just got a questa domanda. So che questo ha 6 anni, ma comunque ... un metodo di istanza è descritto come segue: '- (return_type) firstPartOfMethodName: (first_param_type) first_param secondPartOfMethodName: (second_param_type) second_param ...', dove 'return_type' è il tipo di valore restituito dal metodo, 'first_param_type',' second_param_type', ecc. sono i tipi dei parametri passati al metodo, 'first_param',' second_param', ecc. sono le variabili effettive passate al metodo e 'firstPartOfMethodName: secondPartOfMethodName : ... 'è il nome (o ** firma **) del metodo. –

risposta

36

1) La funzione restituisce una cella per una vista tabella sì? Quindi, l'oggetto restituito è di tipo UITableViewCell. Questi sono gli oggetti che vedi nelle righe della tabella. Questa funzione restituisce fondamentalmente una cella, per una vista tabella. Ma si potrebbe chiedere, come la funzione saprebbe cosa cella per tornare per quello che fila, che viene risolta in 2 ° domanda

2) NSIndexPath è essenzialmente due cose-

  • vostra sezione
  • tuo riga

Poiché la tabella può essere divisa in più sezioni e ciascuna con le proprie righe, questo NSIndexPath consente di identificare con precisione quale sezione e quale riga. Sono entrambi interi. Se sei un principiante, direi di provare con una sola sezione.

Viene chiamato se si implementa il protocollo UITableViewDataSource nel controller di visualizzazione. Un modo più semplice sarebbe aggiungere una classe UITableViewController. Lo consiglio vivamente perché Apple ha del codice scritto per implementare facilmente le funzioni che possono descrivere una tabella. Ad ogni modo, se si sceglie di implementare personalmente questo protocollo, è necessario creare un oggetto UITableViewCell e restituirlo per qualsiasi riga. Dai un'occhiata al suo riferimento di classe per capire la riusabilità perché le celle che vengono visualizzate nella vista tabella vengono riutilizzate più e più volte (questo è un design molto efficiente btw).

Per quanto riguarda quando si hanno due visualizzazioni di tabella, osservare il metodo.La vista tabella è passata ad essa, quindi non dovresti avere problemi a riguardo.

92

cercherò di scomposizione (esempio dalla documention)

/* 
* The cellForRowAtIndexPath takes for argument the tableView (so if the same object 
* is delegate for several tableViews it can identify which one is asking for a cell), 
* and an indexPath which determines which row and section the cell is returned for. 
*/ 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    /* 
    * This is an important bit, it asks the table view if it has any available cells 
    * already created which it is not using (if they are offScreen), so that it can 
    * reuse them (saving the time of alloc/init/load from xib a new cell). 
    * The identifier is there to differentiate between different types of cells 
    * (you can display different types of cells in the same table view) 
    */ 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"]; 

    /* 
    * If the cell is nil it means no cell was available for reuse and that we should 
    * create a new one. 
    */ 
    if (cell == nil) { 

     /* 
     * Actually create a new cell (with an identifier so that it can be dequeued). 
     */ 

     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease]; 

     cell.selectionStyle = UITableViewCellSelectionStyleNone; 

    } 

    /* 
    * Now that we have a cell we can configure it to display the data corresponding to 
    * this row/section 
    */ 

    NSDictionary *item = (NSDictionary *)[self.content objectAtIndex:indexPath.row]; 
    cell.textLabel.text = [item objectForKey:@"mainTitleKey"]; 
    cell.detailTextLabel.text = [item objectForKey:@"secondaryTitleKey"]; 
    NSString *path = [[NSBundle mainBundle] pathForResource:[item objectForKey:@"imageKey"] ofType:@"png"]; 
    UIImage *theImage = [UIImage imageWithContentsOfFile:path]; 
    cell.imageView.image = theImage; 

    /* Now that the cell is configured we return it to the table view so that it can display it */ 

    return cell; 

} 

Questo è un metodo DataSource in modo che sarà chiamato a seconda di quale oggetto si è dichiarato come il DataSource del UITableView. Viene chiamato quando la vista tabella ha effettivamente bisogno di visualizzare la cella sullo schermo, in base al numero di righe e sezioni (che si specifica in altri metodi DataSource).

+0

Dato che questo thread fornisce una buona informazione, vorrei aggiungere un po 'di informazioni che potrebbero essere utili anche. Questo metodo viene anche chiamato se si avvia una ricarica da parte del codice. per esempio. - (void) reloadRowsAtIndexPaths: (NSArray *) indexPaths withRowAnimation: (UITableViewRowAnimation) animazione –

+0

Non dovresti mettere 'cell.selectionStyle = UITableViewCellSelectionStyleNone;' dal blocco if? Quando lo metto dentro, non funziona. –

5

Fondamentalmente sta progettando la cella, Il cellforrowatindexpath viene chiamato per ogni cella e il numero di cella viene trovato da indexpath.row e numero di sezione da indexpath.section. Qui puoi usare un'etichetta, un pulsante o un'immagine testuale tutto ciò che desideri, che viene aggiornato per tutte le righe nella tabella. risposta per la seconda domanda Nella cella per riga in uso percorso dell'indice un'istruzione if

In Objective C

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

NSString *CellIdentifier = @"CellIdentifier"; 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if(tableView == firstTableView) 
    { 
     //code for first table view 
     [cell.contentView addSubview: someView]; 
    } 

    if(tableview == secondTableView) 
    { 
     //code for secondTableView 
     [cell.contentView addSubview: someView]; 
    } 
    return cell; 
} 

In Swift 3,0

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{ 
    let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell! 

    if(tableView == firstTableView) { 
    //code for first table view 
    } 

    if(tableview == secondTableView)  { 
    //code for secondTableView 
    } 

    return cell 
} 
+0

È necessario utilizzare static per NSString * CellIdentifier = @ "CellIdentifier"; Questo delegato è dinamico, quindi tutto ciò che è statico deve essere dichiarato correttamente. – GeneCode

+0

Ma la stringa non cambia sarà sempre "CellIdentifier" ogni volta che la cella viene caricata e non qualcos'altro in modo che la cella venga riutilizzata, correggimi se ho torto. – Koushik

+0

La stringa non cambia, vero. Ma verrà creato molte volte da quando il delegato viene chiamato un sacco di volte. l'uso statico garantisce che la stringa venga creata una volta e venga riutilizzata. – GeneCode

Problemi correlati