开发者

Set switch to On, reload table then insert a new row

开发者 https://www.devze.com 2023-01-31 07:29 出处:网络
I\'ve got an UITableViewController that I use to create settings of my application. There is a section with only one row where I put an UISwitch.

I've got an UITableViewController that I use to create settings of my application.

There is a section with only one row where I put an UISwitch.

How can I insert a new row inside the same section of row with the switch only if the switch in set to YES? And how can I delete this row if the switch is set to NO?

Can anyone help me? Thanks!

I tried to use insertRowsAtIndexPaths:withRowAnimation: method but doesn't work...

This is my settings table code:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = NSLocalizedString(@"Impostazioni", @"");
}


- (void)viewWillAppear:(BOOL)animated {
    [self.tableView reloadData];
}

-(void)addCellToSetCode:(id)sender {

    if ([codeSwitch isOn]) {

        NSIndexPath *updatedIndexPath = [NSIndexPath indexPathForRow:1 inSection:2];
        [self.tableView beginUpdates];
        [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:updatedIndexPath] withRowAnimation:UITableViewRowAnimationTop];
        [self.tableView endUpdates];

        [[NSUserDefaults standardUserDefaults] setBool:codeSwitch.on forKey:@"stateOfSwitch"];
    }
    else {

        NSIndexPath *updatedIndexPath = [NSIndexPath indexPathForRow:1 inSection:2];
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:updatedIndexPath] withRowAnimation:UITableViewRowAnimationTop];
        [self.tableView endUpdates];

        [[NSUserDefaults standardUserDefaults] setBool:codeSwitch.on forKey:@"stateOfSwitch"];
    }
}


#pragma mark -
#pragma mark Table view data source

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

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return NSLocalizedString(@"ListaDesideri", @"");
    }
    if (section == 1) {
        return NSLocalizedString(@"CondivisioneMail", @"");
    }
    if (section == 2) {
        return @"Sicurezza";
    }
    else {
        return nil;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) || (section == 2) || (section == 3) {
        return 2;
    }
    else if (section == 1) {
        return 1;
    }
    else {
        return 1;
    }
}


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

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
    }
    if (indexPath.section == 0 && indexPath.row == 0) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        cell.textLabel.text = NSLocalizedString(@"Ordine", @"");

        if ([[defaults objectForKey:@"ordinaPer"] isEqualToString:@"Nome"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"Nome", @"");
        }
        if ([[defaults objectForKey:@"ordinaPer"] isEqualToString:@"Costo"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"Costo", @"");
        }
        if ([[defaults objectForKey:@"ordinaPer"] isEqualToString:@"Categoria"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"Categoria", @"");
        }
        if ([[defaults objectForKey:@"ordinaPer"] isEqualToString:@"Nome Discendente"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"NomeDiscendente", @"");
        }
        if ([[defaults objectForKey:@"ordinaPer"] isEqualToString:@"Costo Discendente"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"CostoDiscendente", @"");
        }
        if ([[defaults objectForKey:@"ordinaPer"] isEqualToString:@"Categoria Discndente"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"CategoriaDiscendente", @"");
        }

        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if (indexPath.section == 0 && indexPath.row == 1) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        cell.textLabel.text = NSLocalizedString(@"DettagliDesiderio", @"");

        if ([[defaults objectForKey:@"dettagliView"] isEqualToString:@"costoView"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"Costo", @"");
        }
        if ([[defaults objectForKey:@"dettagliView"] isEqualToString:@"descrizioneView"]) {
            cell.detailTextLa开发者_开发知识库bel.text = NSLocalizedString(@"Descrizione", @"");
        }
        if ([[defaults objectForKey:@"dettagliView"] isEqualToString:@"urlView"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"URL", @"");
        }

        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if (indexPath.section == 1 && indexPath.row == 0) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        cell.textLabel.text = NSLocalizedString(@"Shortener", @"");

        if ([[defaults objectForKey:@"linkShortener"] isEqualToString:@"Nessuno"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"Nessuno", @"");
        }
        if ([[defaults objectForKey:@"linkShortener"] isEqualToString:@"is.gd"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"is.gd", @"");
        }
        if ([[defaults objectForKey:@"linkShortener"] isEqualToString:@"bit.ly"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"bit.ly", @"");
        }
        if ([[defaults objectForKey:@"linkShortener"] isEqualToString:@"TinyURL"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"TinyURL", @"");
        }
        if ([[defaults objectForKey:@"linkShortener"] isEqualToString:@"Linkyy"]) {
            cell.detailTextLabel.text = NSLocalizedString(@"Linkyy", @"");
        }

        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if (indexPath.section == 2 && indexPath.row == 0) {
        cell.textLabel.text = @"Access Code";

        codeSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 84, 27)];
        cell.accessoryView = codeSwitch;
        [codeSwitch addTarget:self action:@selector(addCellToSetCode:) forControlEvents:UIControlEventValueChanged];
        codeSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"codeSwitchState"];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if (indexPath.section == 3 && indexPath.row == 0) {
        cell.textLabel.text = NSLocalizedString(@"Supporto", @"");
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if (indexPath.section == 3 && indexPath.row == 1) {
        cell.textLabel.text = NSLocalizedString(@"Informazioni", @"");
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    return cell;
}

EDIT: Updates below...

I solved part of this problem!

I tried to use [self.tableView reloadData] but doesn't work and casually I solved using [self.tableView setNeedsDisplay]...

Now the switch works but if I set to On it and then I go out from app, completely closing it, the switch doesn't work... How can I solve this?

If this can help other, these are pieces of code updated:

-(void)addCellToSetCode:(id)sender {

    if ([codeSwitch isOn]) {

        NSIndexPath *updatedIndexPath = [NSIndexPath indexPathForRow:1 inSection:2];
        [self.tableView beginUpdates];
        [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:updatedIndexPath] withRowAnimation:UITableViewRowAnimationTop];
        [self.tableView endUpdates];

        [self.tableView setNeedsDisplay];

        [[NSUserDefaults standardUserDefaults] setBool:codeSwitch.on forKey:@"codeSwitchState"];
    }
    else {

        NSIndexPath *updatedIndexPath = [NSIndexPath indexPathForRow:1 inSection:2];
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:updatedIndexPath] withRowAnimation:UITableViewRowAnimationTop];
        [self.tableView endUpdates];

        [self.tableView setNeedsDisplay];

        [[NSUserDefaults standardUserDefaults] setBool:codeSwitch.on forKey:@"codeSwitchState"];
    }
}

// tableView:numberOfRowsInSection:
else if (section == 2) {
    return codeSwitch.on ? 2 : 1;
}

// tableView:cellForRowAtIndexPath:
if (indexPath.section == 2 && indexPath.row == 0) {
    cell.textLabel.text = @"Access Code";

    codeSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 84, 27)];
    cell.accessoryView = codeSwitch;
    [codeSwitch addTarget:self action:@selector(addCellToSetCode:) forControlEvents:UIControlEventValueChanged];
    codeSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:@"codeSwitchState"];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
if (indexPath.section == 2 && indexPath.row == 1) {
    if ([codeSwitch isOn]) {
        cell.textLabel.text = @"Set Access Code";
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
}


At least part of your problem (in the updated code) is that you don't create the UISwitch until you create the cell. Your codeSwitch ivar may end up pointing to a different switch as that table row comes in and out of view.

Here's how I'd do this: in tableView:numberOfRowsInSection:, use the NSUserDefaults to see which state the table should be in, instead of using the state of the switch (which may not exist yet). Then, in the switch's action method, call setBool:forKey: for the user defaults before you insert or delete the table row.

In essence, this makes the code follow the MVC model better, because it separates your view (the UISwitch) from the model (the BOOL in user defaults), with the controller (the view controller) in the middle. By confounding the view and the model (the switch and the boolean state), you end up with problems when trying to deal with the state when the view isn't available yet.

BTW, you shouldn't need to call setNeedsDisplay on the table view at all.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号