我使用UIImageView创建了一堆可拖动的图像,我希望保存图像的位置。我已经尝试使用NSUserDefaults保存触摸图像的CGPoint,然后在打开视图控制器时通过CGRectMake加载它的位置。当我运行并打开该视图控制器时出现错误。
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch =[[event allTouches] anyObject];
CGPoint location = [touch locationInView:self.view];
//create location as CGPoint
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:NSStringFromCGPoint(location) forKey:@"key"];
//get location as NSString
[defaults synchronize];
//saves
}
CGPoint中图像的最后位置将转换为NSString并保存。
-(void)viewDidLoad {
[super viewDidLoad];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
CGPoint position = CGPointFromString([defaults objectForKey:@"s1X"]);
//set position as CGpoint
profile[1].frame = CGRectMake(position.x, position.y, 25, 35);
//assign image using the coordinates saved.
}
打开View控制器时,应该加载位置,但是当我打开Viewcontroller时模拟器会停止。请帮我解决这个错误。
编辑:我使用NSMutableArray存储CGPoint,当我运行代码并打开页面模拟器再次终止时(线程1:信号SIGABRT)。而且我找不到为数组分配索引的方法。
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
//UITouch *touch =[[event allTouches] anyObject];
UITouch *touch =[touches anyObject];
CGPoint location = [touch locationInView:self.view];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *dataArray = [[NSMutableArray alloc] init];
for(int i=1; i<12; i++) {
if(profile[i].isExclusiveTouch) {
[dataArray addObject:[NSValue valueWithCGPoint:CGPointMake(location.x, location.y)] objectAtIndex:i];
// how to store the CGPoint at i index?
}
}
[defaults setObject:dataArray forKey:@"key"];
[defaults synchronize];
}
- (void)viewDidLoad {
[super viewDidLoad];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *dataArray = [defaults objectForKey:@"key"];
//Only showed 3 images for example
CGPoint point1 = [[dataArray objectAtIndex:1] CGPointValue];
CGPoint point2 = [[dataArray objectAtIndex:2] CGPointValue];
CGPoint point3 = [[dataArray objectAtIndex:3] CGPointValue];
profile[1].frame = CGRectMake(point1.x-11, point1.y-15, 22, 30);
profile[2].frame = CGRectMake(point2.x-11, point2.y-15, 22, 30);
profile[3].frame = CGRectMake(point3.x-11, point3.y-15, 22, 30);
}
另一个问题 如何将CGPoint分配给索引i?
valueWithCGPoint:CGPointMake(location.x, location.y)]];
//Can't use objectAtIndex or atIndex to assign, there will be error.