0

我有一个简单的问题:我的用户可以在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];
}}
4

3 回答 3

0

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

希望有帮助。

于 2013-06-18T20:42:46.617 回答
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]];
    }
于 2013-06-18T20:44:35.000 回答
0

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

   NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

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

在你的 viewDidLoad: 上这样做:

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

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

干杯

于 2013-06-18T20:45:55.517 回答