2010-04-28 14 views
54

Ho un'applicazione che è viewbased e sto aggiungendo una tableview come sottoview alla vista principale. Ho preso UITableViewDelegate per rispondere ai metodi della tabella. Tutto funziona correttamente, ma voglio selezionare la prima riga o UITableView come predefinita selezionata (evidenziata).Selezionare la prima riga come predefinita in UITableView

Please help me, con quale codice ho bisogno e dove ho bisogno di metterlo.

+0

Sto anche cercando di capire come fare questo. Deve essere impostato dopo che le funzioni di UITableViewDataSource sono state chiamate in modo che la vista tabella abbia qualcosa in essa. UITableView non sembra avere alcun richiamo che si attiva dopo il caricamento dei dati. – jpsimons

risposta

0

Utilizziamo le immagini di sfondo personalizzate per la cella in base al fatto che sia o meno la prima cella ... una cella centrale o l'ultima cella. In questo modo otteniamo un bel aspetto arrotondato sull'intero tavolo. Quando la riga è selezionata, fa scorrere una bella cella 'evidenziata' per dare all'utente il feed back di aver selezionato una cella.

UIImage *rowBackground; 
UIImage *selectionBackground; 
NSInteger sectionRows = [tableView numberOfRowsInSection:[indexPath section]]; 
NSInteger row = [indexPath row]; 

if (row == 0 && row == sectionRows - 1) 
{ 
    rowBackground = [UIImage imageNamed:@"topAndBottomRow.png"]; 
    selectionBackground = [UIImage imageNamed:@"topAndBottomRowSelected.png"]; 
} 
else if (row == 0) 
{ 
    rowBackground = [UIImage imageNamed:@"topRow.png"]; 
    selectionBackground = [UIImage imageNamed:@"topRowSelected.png"]; 
} 
else if (row == sectionRows - 1) 
{ 
    rowBackground = [UIImage imageNamed:@"bottomRow.png"]; 
    selectionBackground = [UIImage imageNamed:@"bottomRowSelected.png"]; 
} 
else 
{ 
    rowBackground = [UIImage imageNamed:@"middleRow.png"]; 
    selectionBackground = [UIImage imageNamed:@"middleRowSelected.png"]; 
} 


((UIImageView *)cell.backgroundView).image = rowBackground; 
((UIImageView *)cell.selectedBackgroundView).image = selectionBackground; 

Se si desidera basta fare la prima cellula, ciò che è in indexPath.row == 0, per utilizzare uno sfondo personalizzato.

Questo deriva da Matt Gallagher excellent site

-1

Si può fare in questo modo:

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    NSIndexPath *ip=[NSIndexPath indexPathForRow:0 inSection:0]; 
    [myTableView selectRowAtIndexPath:ip animated:YES scrollPosition:UITableViewScrollPositionBottom]; 
} 
+0

L'ho aggiunto, ma non funziona. –

+0

Questo perché viewDidLoad viene chiamato prima che tableview possa creare le sue celle. Usa performSelector: onObject: afterDelay: per chiamarlo dopo averlo caricato, o provare viewDidAppear: come suggerito altrove. – avance

+1

controlla la mia risposta sopra. non utilizzare mai questo in viewDidLoad: chiamare questa funzione in viewDidAppear per risultato fine. –

105
- (void)viewDidAppear:(BOOL)animated { 
    [super viewDidAppear:animated]; 
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0]; 
    [myTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionBottom]; 
} 

Il modo migliore per utilizzare questo nel codice, se si desidera selezionare qualsiasi riga di default , utilizzare in viewDidAppear.

+4

La mia cella non selezionerebbe in viewDidAppear per qualche strana ragione, ma funziona bene in viewWillAppear – RyanG

+1

L'app potrebbe bloccarsi se c'è qualche filtro che sta accadendo e risulta in una matrice vuota. È necessario aggiungere un controllo all'inizio –

+0

Sto utilizzando questo approccio per selezionare una cella al primo posto, quindi sto chiamando il delegato, ma la cella selezionata con selectRowAtIndexPath non viene mai deselezionata. Non consentire MultipleSelection. Qualsiasi aiuto? per favore, grazie. – Frade

8
- (void)viewWillAppear:(BOOL)animated 
    { 

     [super viewWillAppear:animated]; 

    // assuming you had the table view wired to IBOutlet myTableView 

     // and that you wanted to select the first item in the first section 

     [myTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:0]; 
    } 
5
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    self.detailViewController = (DetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController]; 

    if([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad){ 
     NSIndexPath* indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 
     [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionTop]; 
     [self tableView:self.tableView didSelectRowAtIndexPath:indexPath]; 
    } 
} 
3

Ecco come fare a Swift 1.2:

override func viewWillAppear(animated: Bool) { 
    let firstIndexPath = NSIndexPath(forRow: 0, inSection: 0) 
    self.tableView.selectRowAtIndexPath(firstIndexPath, animated: true, scrollPosition: .Top) 
} 
1

Per solamente selezionare la prima cella la prima volta che la tabella è caricata, si potrebbe pensare che l'utilizzo viewDidLoad è il posto giusto per andare, ma, in quel momento di esecuzione, la tabella non ha caricato il suo contenuto, quindi non funzionerà (e probabilmente bloccherà l'app dal momento che il NSIndexPath punterà a una cella inesistente).

Una soluzione alternativa consiste nell'utilizzare una variabile che indica che la tabella è stata caricata prima e che esegue il lavoro di conseguenza.

@implementation MyClass { 
    BOOL _tableHasBeenShownAtLeastOnce; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    _tableHasBeenShownAtLeastOnce = NO; // Only on first run 
} 

- (void)viewDidAppear:(BOOL)animated 
{ 
    [super viewDidAppear:animated]; 

    if (! _tableHasBeenShownAtLeastOnce) 
    { 
     _tableHasBeenShownAtLeastOnce = YES; 
     BOOL animationEnabledForInitialFirstRowSelect = YES; // Whether to animate the selection of the first row or not... in viewDidAppear:, it should be YES (to "smooth" it). If you use this same technique in viewWillAppear: then "YES" has no point, since the view hasn't appeared yet. 
     NSIndexPath *indexPathForFirstRow = [NSIndexPath indexPathForRow:0 inSection: 0]; 

     [self.tableView selectRowAtIndexPath:indexPathForFirstRow animated:animationEnabledForInitialFirstRowSelect scrollPosition:UITableViewScrollPositionTop]; 
    } 
} 

/* More Objective-C... */ 

@end 
9

Swit 3.0 aggiornamento Soluzione

let indexPath = IndexPath(row: 0, section: 0) 
tblView.selectRow(at: indexPath, animated: true, scrollPosition: .bottom) 
1

Ecco la mia soluzione per SWIFT 3.0:

var selectedDefaultIndexPath = false 


override func viewDidAppear(_ animated: Bool) { 
    super.viewDidAppear(animated) 

    if dataSource.isEmpty == false, selectedDefaultIndexPath == false { 
     let indexPath = IndexPath(row: 0, section: 0) 
     // if have not this, cell.backgroundView will nil. 
     tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) 
     // trigger delegate to do something. 
     _ = tableView.delegate?.tableView?(tableView, willSelectRowAt: indexPath) 
     selectedDefaultIndexPath = true 
    } 
} 

func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { 
    let cell = tableView.cellForRow(at: indexPath) 
    cell?.selectedBackgroundView?.backgroundColor = UIColor(hexString: "#F0F0F0") 

    return indexPath 
} 
Problemi correlati