将开关设置为“开”,重新加载表,然后插入新行

发布于 2024-10-09 03:26:21 字数 8848 浏览 8 评论 0原文

我有一个 UITableViewController,用于创建应用程序的设置。

有一个部分只有一行,我在其中放置了 UISwitch。
仅当开关设置为 YES 时,如何在具有开关的行的同一部分中插入新行?如果开关设置为“否”,如何删除这一行?

有人可以帮助我吗?谢谢!

我尝试使用 insertRowsAtIndexPaths:withRowAnimation: 方法但不起作用...
这是我的设置表代码:

- (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.detailTextLabel.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;
}

编辑:下面更新...

我解决了这个问题的一部分!
我尝试使用 [self.tableView reloadData] 但不起作用,我随便使用 [self.tableView setNeedsDisplay] 解决了...

现在开关可以工作,但如果我设置为“On”,然后我从应用程序中退出,完全关闭它,开关不起作用...我该如何解决这个问题?

如果这可以帮助其他人,这些是更新的代码片段:

-(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;
    }
}

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.detailTextLabel.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;
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

灯角 2024-10-16 03:26:21

至少部分问题(在更新的代码中)是在创建单元格之前不创建 UISwitch。当该表行进入和退出视图时,您的 codeSwitch ivar 最终可能会指向不同的开关。

我的做法如下:在 tableView:numberOfRowsInSection: 中,使用 NSUserDefaults 来查看表应处于哪个状态,而不是使用开关的状态(可能尚不存在)。然后,在开关的操作方法中,在插入或删除表行之前调用 setBool:forKey: 以获取用户默认值。

从本质上讲,这使得代码更好地遵循 MVC 模型,因为它将视图(UISwitch)与模型(用户默认值中的 BOOL)分开,并且 em>控制器(视图控制器)在中间。通过混淆视图和模型(开关和布尔状态),当视图尚不可用时尝试处理状态时,您最终会遇到问题。

顺便说一句,您根本不需要在表格视图上调用 setNeedsDisplay

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文