保存UIImageView的位置

时间:2013-04-07 11:55:11

标签: ios objective-c

我有几个UIImageViews,用户可以拖动,缩放和旋转。我希望当用户导航到另一个视图并返回时,位置,大小和角度会持续存在。我如何实现这一目标?

我使用以下代码进行平移,旋转和缩放

- (void)panPiece:(UIPanGestureRecognizer *)gestureRecognizer
{
UIView *piece = [gestureRecognizer view];

[self adjustAnchorPointForGestureRecognizer:gestureRecognizer];

if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
    CGPoint translation = [gestureRecognizer translationInView:[piece superview]];

    [piece setCenter:CGPointMake([piece center].x + translation.x, [piece center].y + translation.y)];
    [gestureRecognizer setTranslation:CGPointZero inView:[piece superview]];
}
}


- (void)rotatePiece:(UIRotationGestureRecognizer *)gestureRecognizer
{
[self adjustAnchorPointForGestureRecognizer:gestureRecognizer];

if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
    [gestureRecognizer view].transform = CGAffineTransformRotate([[gestureRecognizer view] transform], [gestureRecognizer rotation]);
    [gestureRecognizer setRotation:0];
}
}


- (void)scalePiece:(UIPinchGestureRecognizer *)gestureRecognizer
{
[self adjustAnchorPointForGestureRecognizer:gestureRecognizer];

if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
    [gestureRecognizer view].transform = CGAffineTransformScale([[gestureRecognizer view] transform], [gestureRecognizer scale], [gestureRecognizer scale]);
    [gestureRecognizer setScale:1];
}
}

1 个答案:

答案 0 :(得分:1)

根据您的需要,您可以创建方法,将其作为另一种目标方法添加到所有手势识别器。

E.g。

[panGestureRecognizer addTarget: self action: @selector(onGestureRecognizerEnd:)];
[rotationGestureRecognizer addTarget: self action: @selector(onGestureRecognizerEnd:)];
[pinchGestureRecognizer addTarget: self action: @selector(onGestureRecognizerEnd:)];


该方法的示例实现可以是:

- (void)onGestureRecognizerEnd: (UIGestureRecognizer *)gestureRecognizer
{
    switch ( gestureRecognizer.state )
    {
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateFailed:
        {
            [self _saveViewPosition: gestureRecognizer.view];
            break;
        }
        default:
        {
            break;
        }
    }
}


你可以像这样实现

_saveViewPosition:方法:

- (void)_saveViewPosition: (UIView *)view
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    [defaults setObject: [NSKeyedArchiver archivedDataWithRootObject: [NSValue valueWithCGPoint: view.center]]
                 forKey: [self _centerKeyForView: view]];
    [defaults setObject: [NSKeyedArchiver archivedDataWithRootObject: [NSValue valueWithCGAffineTransform: view.transform]]
                 forKey: [self _transformKeyForView: view]];
}


有关详细信息,请查看Xcode project

BR