2014-07-26 3 views
7

Quindi ho implementato un UIViewController con una tableview, e fondamentalmente si carica come un set di "filtri" per la mia vista uicollection.Salva i segni di spunta accessori su uitableview quando gli utenti caricano la vista più volte

Ora, quando clicco sui segni di spunta nella mia Tableview, si "filtri" le mie cellule di conseguenza, ma ora quando ricarico di nuovo la vista che voglio per visualizzare i più recenti "segni di spunta" Ho usato, o "filtri ".

Ho visto questo essere implementato con NSUserDefaults, ma non sono stato in grado di implementarlo con successo.

Se qualcuno potesse aiutarmi, sarà molto apprezzato.

CODICE

FiltersViewController.m:

#import "FiltersViewController.h" 

@interface FiltersViewController() 

@property (nonatomic, strong) NSMutableSet *selectedRowObjects; 
//@property (nonatomic, strong) NSArray *filters; 

@end 

@implementation FiltersViewController 


- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    self.selectedRowObjects = [NSMutableSet setWithCapacity:10]; 
} 

- (IBAction)filtersSelected:(id)sender { 
    [self.delegate filtersSelected:self.selectedRowObjects]; 
} 

- (IBAction)cancelFilterSelection:(id)sender { 
    [self.delegate filterSelectionCancelled]; 
} 

- (NSString *)getKeyForIndex:(int)index 
{ 
    return [NSString stringWithFormat:@"KEY%d",index]; 
} 

- (BOOL) getCheckedForIndex:(int)index 
{ 
    if([[[NSUserDefaults standardUserDefaults] valueForKey:[self getKeyForIndex:index]] boolValue]==YES) 
    { 
     return YES; 
    } 
    else 
    { 
     return NO; 
    } 
} 

- (void) checkedCellAtIndex:(int)index 
{ 
    BOOL boolChecked = [self getCheckedForIndex:index]; 

    [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:!boolChecked] forKey:[self getKeyForIndex:index]]; 
    [[NSUserDefaults standardUserDefaults] synchronize]; 
} 


#pragma mark - Table view data source 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return 10; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"filter" forIndexPath:indexPath]; 
    cell.textLabel.text = [NSString stringWithFormat:@"%u", indexPath.row]; 



    return cell; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 


    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 
    NSString *obj = cell.textLabel.text; 

    if (cell.accessoryType == UITableViewCellAccessoryCheckmark) { 
     cell.accessoryType = UITableViewCellAccessoryNone; 
     [self.selectedRowObjects removeObject:obj]; 
    } 
    else { 
     cell.accessoryType = UITableViewCellAccessoryCheckmark; 
     [self.selectedRowObjects addObject:obj]; 
    } 

    [tableView deselectRowAtIndexPath:indexPath animated:YES]; 

} 
@end 
+0

Si sta recuperando e impostando i valori predefiniti dell'utente in metodi a cui non si fa riferimento da nessun'altra parte nel codice. – duci9y

+0

@ duci9y ok potresti spiegarmelo usando il codice? Capisco cosa stai dicendo –

+0

NSAccedi ai valori userDefault (in diversi punti) per vedere se sono ciò che ti aspetti .. –

risposta

3

Hai fatto quasi tutto a destra. Hai solo bisogno di mettere la tua logica per leggere i valori NSUserDefault (per le caselle selezionate) nel metodo delegato cellForRowAtIndexPath. Questo è il metodo che disegna UITableViewCells quando vengono visualizzati sullo schermo. Qualcosa del genere:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"filter" forIndexPath:indexPath]; 
    cell.textLabel.text = [NSString stringWithFormat:@"%u", indexPath.row]; 

    if ([self getCheckedForIndex:indexPath.row]) 
    { 
     //code to set checkbox 
    } 

    return cell; 
} 
+0

grazie! Proverò a vedere se riesco a implementare questo –

+0

questo non ha funzionato affatto. Ora, quello che succede è quando carico la vista tabella mostra tutti i segni di spunta ogni volta che lo apro. –

+0

Immagino di non essere chiaro sulle specifiche. Forse potresti allegare alcune schermate che mostrano esattamente cosa stai cercando di realizzare? – Jordan

4

è necessario controllare anche cellForRowAtIndexPath. Scrivere questo codice in questo

if([[NSUserDefaults standardUserDefaults] objectForKey:[self getKeyForIndex:indexPath.row]]) 
{ 
    cell.accessoryType = UITableViewCellAccessoryCheckmark; 
} 
else 
{ 
    cell.accessoryType = UITableViewCellAccessoryNone; 
} 

E sì non dimenticare di chiamare questo metodo in didSelectRowAtIndexPath

[self checkedCellAtIndex:indexPath.row]; 

Enjoy.

+0

questo non ha funzionato affatto. Ora, quello che succede è quando carico la vista tabella mostra tutti i segni di spunta ogni volta che lo apro. –

+0

il tuo requisito è che il fratello va bene, ma devi rimuovere nsuserdefault quando si carica provare questo [[NSUserDefaults standardUserDefaults] removeObjectForKey: @ "passa la chiave qui"]; –

+0

Il tuo requisito è quello di memorizzare in NSUserDefault, se non usi NSUserDefault, allora è molto facile con Array –

1

Hai implementato perfettamente. Hai solo bisogno di modificare voi cellForRowAtIndexPath Metodo

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"filter" forIndexPath:indexPath]; 
    cell.textLabel.text = [NSString stringWithFormat:@"%u", indexPath.row]; 

BOOL checked = [self getCheckedForIndex:indexPath.row]; 
    if(checked) 
     cell.accessoryType = UITableViewCellAccessoryCheckmark; 
    else 
     cell.accessoryType = UITableViewCellAccessoryNone; 


    return cell; 
} 

anche chiamare [self checkedCellAtIndex:indexPath.row]; da didSelectRowAtIndexPath metodo UITableView.

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

NSString *simpleTableIdentifier = @"cell"; 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; 

if (cell == nil) 
{ 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier]; 
} 
cell.textLabel.text = ArrayOfObject[indexPath.row]; 
NSUserDefaults *ud =[NSUserDefaults standardUserDefaults]; 
if([[ud objectForKey:@"selectedObjectKey "]isEqualToString:ArrayOfObject[indexPath.row]]) 
{ 
    cell.accessoryType = UITableViewCellAccessoryCheckmark; 
} 
else 
{ 
    cell.accessoryType = UITableViewCellAccessoryNone; 
} 
return cell; 


} 
1

Il modo migliore per risparmiare tableView CheckMark con NSUserDefaults

@interface TableViewController(){ 
    NSArray *TableTitles; 
    NSMutableArray *SelectedRows; 
} 

viewDidLoad

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    // table view array 
    TableTitles = [NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil]; 

    NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults]; 
    SelectedRows = [NSMutableArray arrayWithArray:[userDef objectForKey:@"SelectedRows"]]; 
} 

cellForRowAtIndexPath

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; 

    cell.textLabel.text = TableTitles[indexPath.row]; 

    NSNumber *obj = [NSNumber numberWithInteger:indexPath.row]; 
    if ([SelectedRows containsObject:obj]) 
    { 
     cell.accessoryType = UITableViewCellAccessoryCheckmark; 
    } 
    else 
    { 
     cell.accessoryType = UITableViewCellAccessoryNone; 
    } 
    return cell; 
} 

didSelectRowAtIndexPath

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ 
    NSNumber *obj = [NSNumber numberWithInteger:indexPath.row]; 
    if ([SelectedRows containsObject:obj]) 
    { 
     [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryNone; 
     [SelectedRows removeObject:obj]; 
     [tableView reloadData]; 
    }else{ 
     [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark; 
     [SelectedRows addObject:obj]; 
     [tableView reloadData]; 
    } 

    NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults]; 
    [userDef setObject:SelectedRows forKey:@"SelectedRows"]; 
    [userDef synchronize]; 
} 

aggiornato ...

ho aggiornato tutto il codice con un nuovo modo, è il modo migliore per risparmiare Tableview segni di spunta ed è ora facile ed efficiente, ora solo un array viene utilizzato per il salvataggio e il caricamento, il codice ha ridotto troppo :)

+0

Bellissima risposta - +1 –

0

È dovrebbe caricare i dati in NSUserDefaults mentre chiamata cellForRowAtIndexPath

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"filter" forIndexPath:indexPath]; 
    cell.textLabel.text = [NSString stringWithFormat:@"%u", indexPath.row]; 

    //You should set accessoryType here by NSUserDefaults data 
    if ([self getCheckedForIndex:indexPath.row]) { 
     cell.accessoryType = UITableViewCellAccessoryCheckmark; 
    } 
    else{ 
     cell.accessoryType = UITableViewCellAccessoryNone; 
    } 


    return cell; 
} 
+0

Ottima risposta - +1 –

0

Penso che quello che stai cercando è quello di ottenere lo stato corrente della tabella per i filtri quando entrare e uscire dal panorama. È necessario utilizzare - (void)viewWillDisappear:(BOOL)animated per salvare lo stato corrente della tabella su NSUserDefaults, quindi utilizzare - (void)viewDidLoad e - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath per impostare il segno di spunta quando la tabella viene ricaricata.

@interface FiltersViewController() { 
    NSMutableArray *_filterStates; 
} 

@end 

- (void)viewDidLoad { 
    filterStates = [[NSMutableArray alloc] init]; 

    // get state of your current filters in NSUserDefaults, these should be stored as [NSNumber numberWithBool:] 
} 

- (void)viewWillDisappear:(BOOL)animated { 
    // store all of your filters into your NSUserDefaults as [NSNumber numberWithBool:] 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    // get your cell from the table 

    BOOL isChecked = [[_filterStates objectAtIndex:indexPath.row] boolValue]; 

    // set the checkmark based on the current state for this filter 
}