如何保存/重新加载UIView中的各种按钮

时间:2013-06-18 20:12:44

标签: ios uiview

我有一个简单的问题:我的用户可以在UIView中添加按钮。我会使用NSUserDefault保存各种按钮,然后在应用程序启动时(而不是后台)在UIView重新加载它们。我该怎么办?

    -(void)AddButton:(UIButton*)sender {
         CountButton++;
           if (CountButton< 11) {
            button2 = [UIButton buttonWithType:UIButtonTypeCustom];
            button2.frame = CGRectMake(20, 80, 120, 80);
            UIImage *buttonImage = [UIImage imageNamed:@"image"];
            [button2 setBackgroundImage:buttonImage forState:UIControlStateNormal];
            NSString* buttonTitle = [NSString stringWithFormat:@"Button%d", CountButton];
            [button2 setTitle:buttonTitle forState:UIControlStateNormal];
            NSString *selectorName = [NSString stringWithFormat:@"ButtonAdd%d:", CountButton];

    [button2 addTarget:self action:NSSelectorFromString(selectorName)forControlEvents:UIControlEventTouchUpInside];
}}

3 个答案:

答案 0 :(得分:0)

在控制器的viewDidLoad中,检查先前存储的NSUserDefault值,并以编程方式创建许多按钮,并将它们作为子视图添加到控制器的视图中。

希望有所帮助。

答案 1 :(得分:0)

NSUserDefaults适用于小块数据。保存众多按钮可能不是NSUserDefaults的最佳选择。请考虑使用文件。您可以在代码中的适当时间加载文件,以显示已保存的按钮。

首先创建按钮,就像发布的代码一样:

button2 = [UIButton buttonWithType:UIButtonTypeCustom];
button2.frame = CGRectMake(20, 80, 120, 80);
//etc...

使用按钮编写文件:

NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                   NSUserDomainMask,
                                                                   YES);
NSMutableString *documentDirectory = [documentDirectories objectAtIndex:0];
NSArray *myArray = [[NSArray alloc] initWithObjects:myButton1, myButton2, myButton3, nil];
NSString *filePath = [documentDirectory stringByAppendingPathComponent:@"UserButtons"];
BOOL fileError = [myArray writeToFile:filePath atomically:YES];
NSLog(@"User data to file successful: %@",(fileError ? @"Yes" : @"No"));

要阅读文件:

NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                       NSUserDomainMask,
                                                                       YES);
    NSMutableString *documentDirectory = [documentDirectories objectAtIndex:0];
    NSString *myPath = [documentDirectory stringByAppendingPathComponent:@"UserButtons"];
    NSArray *fileArray = [[NSArray alloc] initWithContentsOfFile:myPath];
    if([fileArray count] > 0)
    {
        // place your buttons back into the view.
        // [self.view addSubview:[fileArray objectAtIndex:0]];
    }

答案 2 :(得分:0)

将所有按钮添加到阵列。然后将数组添加到UserDefault:

   NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

            [userDefaults setObject:buttonArray
                             forKey:@"buttons"];
            [userDefaults synchronize];
在viewDidLoad上

: 这样做:

buttonsArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"buttons"];

最后,在数组中循环并添加每个按钮

干杯