如何保存UIButton

时间:2013-06-19 21:26:41

标签: ios uibutton plist

我可以在我的uiview上通过AddButton创建3个不同的按钮。当我再次关闭我的应用程序时,3个按钮消失。然后我的用户被迫重新创建3个按钮。如何保存用户创建的按钮?我正在尝试保存用户创建的按钮,但我还没弄清楚我该怎么做。你可以帮我一个忙吗? 对不起,但我不知道如何格式化我的代码!!!

-(void) AddButton: (UIButton *)sender {
CountButton ++;
if (CountButton <4) {
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: @"%d ButtonAdd:" CountButton];
[button2 addTarget: self action: NSSelectorFromString (selectorName) forControlEvents:UIControlEventTouchUpInside];

NSArray * = documentDirectories NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSMutableString * documentDirectory = [documentDirectories objectAtIndex: 0];
NSArray * myArray = [[NSArray alloc] initWithObjects: Button1, Button2, Button3, nil];
NSString * filePath = [documentDirectory stringByAppendingPathComponent: @ "UserButtons"];
BOOL FileError = [myArray writeToFile: filePath atomically: YES];
NSLog (@ "User date to file successful:% @", (FileError? @"Yes": @"No"));
}
}
-(void) viewDidLoad {
[super viewDidLoad];
 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 buttons back into the view.
[self.view addSubview: [fileArray objectAtIndex: 0]];
}
}

1 个答案:

答案 0 :(得分:1)

您需要了解有关Plists的更多信息。他们不能存储除NSDictionary, NSArray, NSString, NSNumber, NSDate, NSData之外的任何内容。因此,您无法在其中存储UIButtons。相反,您需要存储允许您重建每个按钮的数据。例如,将其框架存储为一系列NSNumber,其标题和选择器名称为NSString s。