【发布时间】:2015-07-20 19:57:27
【问题描述】:
我想要完成的是构建一个 UITableView,其中每个单元格的右侧都有一个 UISwitch,当用户再次打开应用程序时,这些开关将保持在相应索引路径的开/关位置。
我创建了一个布尔值的 NSArray 并将它们保存到 NSUser 默认值,但是在循环返回它们以使布尔值位于正确的索引以将单元格切换开关设置为打开或关闭时遇到了一些障碍。
创建具有索引路径属性的自定义单元格会更好吗?那么只是有一种方法可以将布尔值保存到索引路径吗?
我对编程比较陌生,所以我想知道一些更高级的人认为最快和最简单的方法是什么。
非常感谢!
这是我的布尔控制器,保存方法是公开的,
#import "BoolController.h"
static NSString *const boolArrayKey = @"boolArrayKey";
@implementation BoolController
+ (BoolController *)sharedInstance {
static BoolController *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [BoolController new];
});
return sharedInstance;
}
- (void)saveBool:(BOOL)boolean {
NSArray *arrayOfBooleans = [[NSArray alloc]init];
arrayOfBooleans = [arrayOfBooleans arrayByAddingObject:[NSNumber numberWithBool:boolean]];
[[NSUserDefaults standardUserDefaults]setObject:arrayOfBooleans forKey:boolArrayKey];
[[NSUserDefaults standardUserDefaults]synchronize];
}
- (NSArray *)booleans {
return [[NSUserDefaults standardUserDefaults]objectForKey:boolArrayKey];
}
@end
这是我在索引路径方法中的行单元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
UISwitch *toggleSwitch = [[UISwitch alloc]initWithFrame:CGRectMake(50, 10, 50, 30)];
[cell addSubview:toggleSwitch];
if (toggleSwitch.isOn == YES) {
[[BoolController sharedInstance]saveBool:YES];
}
if (toggleSwitch.isOn == NO) {
[[BoolController sharedInstance]saveBool:NO];
}
return cell;
}
【问题讨论】:
-
我更新了代码,索引路径方法的行单元格不完整,因为我一直在玩不同的东西,我只是不知道从哪里开始。
标签: ios objective-c uitableview boolean nsarray