我在我的应用程序中移动图像,效果很好。问题是当用户返回该视图时,我想将图像保留在适当的位置。目前,我正在使用一个字符串来保存图像中心:
NSString *centre = NSStringFromCGPoint(image.center);
我有一个名为 theCentre 的 NSUserDefault 变量:
theCentre = [NSUserDefaults standardUserDefaults];
我尝试使用以下方法保存:
[theCentre setObject:centre forKey:@"centre"];
当我输出日志时,我得到以下信息:
{280, 320}
这很棒。在 viewDidLoad 中,我尝试了完全相同的日志,它正在返回(null)。我认为这意味着它没有正确保存 theCentre。我是否在这里遗漏了一些基本的东西,因为我在我的应用程序的其他地方使用了 NSUserDefaults 并且它工作正常。提前谢谢了。
编辑:这是尝试帮助调试的整个代码:)
-(void)getBounds
{
lowerBoundX = 250;
upperBoundX = 310;
lowerBoundY = 290;
upperBoundY = 350;
}
#pragma mark -
#pragma mark UIPanGestureRecognizer selector
- (void) dragGesture:(UIPanGestureRecognizer *) panGesture
{
[self getBounds];
CGPoint translation = [panGesture translationInView:self.view];
switch (panGesture.state) {
case UIGestureRecognizerStateBegan:{
originalCentre = dragImage.center;
}
break;
case UIGestureRecognizerStateChanged:{
dragImage.center = CGPointMake(dragImage.center.x + translation.x,
dragImage.center.y + translation.y);
}
break;
case UIGestureRecognizerStateEnded:{
if (((dragImage.center.x >= lowerBoundX) && (dragImage.center.y >= lowerBoundY) &&
(dragImage.center.x <= upperBoundX) && (dragImage.center.y <= upperBoundY))) {
dragImage.center = CGPointMake(280, 320);
[dragImage setUserInteractionEnabled:NO];
theCentre = [NSUserDefaults standardUserDefaults];
NSString *centre = NSStringFromCGPoint(dragImage.center);
[theCentre setObject:centre forKey:@"centre"];
NSLog(@"%@", [theCentre objectForKey:@"centre"]);
[theCentre synchronize];
break;
}
[UIView animateWithDuration:0.5
animations:^{
dragImage.center = originalCentre;
}
completion:^(BOOL finished){
}];
}
break;
default:
break;
}
[panGesture setTranslation:CGPointZero inView:self.view];
}
-(IBAction)clear{
[UIImageView animateWithDuration:0.5 animations:^{
dragImage.center = CGPointMake(100, 200);
}];
[dragImage setUserInteractionEnabled:YES];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSLog(@"%@", [theCentre objectForKey:@"centre"]);
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(dragGesture:)];
[dragImage addGestureRecognizer:panGesture];
[dragImage setUserInteractionEnabled:YES];
}