UIViewController被解除后,如何保存和恢复每个UISwitch状态



编辑:我还需要答案!

我有两个UIViewControllers(我们称它们为ParentVCSecondVC

SecondVC上有11个UISwitch元素,还有一个按钮用于将每个UISwitch的状态从SecondVC发送到ParentVC。

在parentVC中,我需要一个NSArray,它将包含NSDictionary的密钥(在IBAction中描述)。我有IBA操作:

NSDictionary *resultDic = [NSDictionary dictionaryWithObjectsAndKeys:
                               [NSNumber numberWithBool: [_cafeSwitch isOn]], @"Cafe",
                               .....
                               [NSNumber numberWithBool: [_bowlingSwitch isOn]], @"BowlingClub",
                               nil];
    NSMutableArray *resultArray = [[NSMutableArray alloc] init];
    for (NSString *key in resultDic) {
        NSNumber *value = [resultDic valueForKey:key];
        if ([value compare:[NSNumber numberWithInt:1]] == NSOrderedSame)
            [resultArray addObject:key];
    }
    [_delegate sendSelectedPlaceTypeArray:[NSArray arrayWithArray:resultArray]];
    [self dismissViewControllerAnimated:YES completion:^{}];

方法sendSelectedPlaceTypeArray是在ParentVC中接收此NSArray的委托方法。默认状态下会选择所有切换器。在ParentVC中,我实现了委托方法:

- (void)sendSelectedPlaceTypeArray:(NSArray *)placeTypeArray {
    filteredPlaceTypeArray_ = placeTypeArray;
}

默认情况下,filteredPlaceTypeArray_包含所有11个位置类型。

filteredPlaceTypeArray_ = [NSArray arrayWithObjects:@"Cafe", ... ,@"BowlingClub", nil];

提出SecondVC的方法是:

- (IBAction)showPlaceTypeFilter:(id)sender {
    UIStoryboard *iPhoneStoryboard = [UIStoryboard storyboardWithName:@"Main_iPhone" bundle:nil];
    PlaceTypeFilterViewController *destViewController = [iPhoneStoryboard instantiateViewControllerWithIdentifier:@"PlaceTypeFilterViewController"];
    destViewController.delegate = self;
    destViewController.currentFilteredPlaceTypesArray = filteredPlaceTypeArray_;
    [self presentViewController:destViewController animated:YES completion:nil];
}

我有很多问题:

  1. 使用过滤器是一个好的解决方案吗
  2. 如果SecondVC被调用两次或两次以上,例如11个UISwitch元素中的2个被更改,如何保存和恢复UISwitch元素的值?对此,最好的解决方案是什么?因为当SecondVC出现时,所有UISwitch元素都被选中了

我希望我的问题是正确的,谢谢,阿特姆。

据我所知,以下是从视图中获取所有对象的方法:

for (UISwitch *mySwitch in [self.view subviews]) {
    if ([mySwitch isKindOfClass:[UISwitch class]]) {
        NSLog(@"State == %@",[mySwitch description]);
        //Do what ever you want to do with your switches 
    }
}

编辑:此答案与编辑前的原始问题有关。

如何以编程方式设置每个UISWitch的状态

最新更新