Search code examples
iphoneuiviewtransformuigesturerecognizercenter

Loading UIView transform & center from settings gives different position


I'm using pan, pinch, and rotate UIGestureRecognizers to allow the user to put certain UI elements exactly where they want them. Using the code from here http://www.raywenderlich.com/6567/uigesturerecognizer-tutorial-in-ios-5-pinches-pans-and-more (or similar code from here http://mobile.tutsplus.com/tutorials/iphone/uigesturerecognizer/) both give me what I need for the user to place these UI elements as they desire.

When the user exits "UI layout" mode, I save the UIView's transform and center like so:

NSString *transformString = NSStringFromCGAffineTransform(self.transform);
[[NSUserDefaults standardUserDefaults] setObject:transformString forKey:@"UItransform", suffix]];

NSString *centerString = NSStringFromCGPoint(self.center);
[[NSUserDefaults standardUserDefaults] setObject:centerString forKey:@"UIcenter"];

When I reload the app, I read the UIView's transform and center like so:

NSString *centerString = [[NSUserDefaults standardUserDefaults] objectForKey:@"UIcenter"];
if( centerString != nil )
    self.center = CGPointFromString(centerString);

NSString *transformString = [[NSUserDefaults standardUserDefaults] objectForKey:@"UItransform"];

if( transformString != nil )
    self.transform = CGAffineTransformFromString(transformString);

And the UIView ends up rotated and scaled correctly, but in the wrong place. Further, upon entering "UI layout" mode again, I can't always grab the view with the various gestures (as though the view as displayed is not the view as understood by the gesture recognizer?)

I also have a reset button that sets the UIView's transform to the identity and its center to whatever it is when it loads from the NIB. But after loading the altered UIView center and transform, even the reset doesn't work. The UIView's position is wrong.

My first thought was that since those gesture code examples alter center, that rotations must be happening around different centers (assuming some unpredictable sequence of moves, rotations, and scales). As I don't want to save the entire sequence of edits (though that might be handy if I want to have some undo feature in the layout mode), I altered the UIPanGestureRecognizer handler to use the transform to move it. Once I got that working, I figured just saving the transform would get me the current location and orientation, regardless of in what order things happened. But no such luck. I still get a wacky position this way.

So I'm at a loss. If a UIView has been moved and rotated to a new position, how can I save that location and orientation in a way that I can load it later and get the UIView back to where it should be?

Apologies in advance if I didn't tag this right or didn't lay it out correctly or committed some other stackoverflow sin. It's the first time I've posted here.

EDIT

I'm trying the two suggestions so far. I think they're effectively the same thing (one suggests saving the frame and the other suggests saving the origin, which I think is the frame.origin).

So now the save/load from prefs code includes the following.

Save:

NSString *originString = NSStringFromCGPoint(self.frame.origin);
[[NSUserDefaults standardUserDefaults] setObject:originString forKey:@"UIorigin"];

Load (before loading the transform):

NSString *originString = [[NSUserDefaults standardUserDefaults] objectForKey:@"UIorigin"];
if( originString ) {
    CGPoint origin = CGPointFromString(originString);
    self.frame = CGRectMake(origin.x, origin.y, self.frame.size.width, self.frame.size.height);
}

I get the same (or similar - it's hard to tell) result. In fact, I added a button to just reload the prefs, and once the view is rotated, that "reload" button will move the UIView by some offset repeatedly (as though the frame or transform are relative to itself - which I'm sure is a clue, but I'm not sure what it's pointing to).

EDIT #2

This makes me wonder about depending on the view's frame. From Apple http://developer.apple.com/library/ios/#documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/WindowsandViews/WindowsandViews.html#//apple_ref/doc/uid/TP40009503-CH2-SW6 (emphasis mine):

The value in the center property is always valid, even if scaling or rotation factors have been added to the view’s transform. The same is not true for the value in the frame property, which is considered invalid if the view’s transform is not equal to the identity transform.

EDIT #3

Okay, so when I'm loading the prefs in, everything looks fine. The UI panel's bounds rect is {{0, 0}, {506, 254}}. At the end of my VC's viewDidLoad method, all still seems okay. But by the time things actually are displayed, bounds is something else. For example: {{0, 0}, {488.321, 435.981}} (which looks like how big it is within its superview once rotated and scaled). If I reset bounds to what it's supposed to be, it moves back into place.

It's easy enough to reset the bounds to what they're supposed to be programatically, but I'm actually not sure when to do it! I would've thought to do it at the end of viewDidLoad, but bounds is still correct at that point.

EDIT #4

I tried capturing self.bounds in initWithCoder (as it's coming from a NIB), and then in layoutSubviews, resetting self.bounds to that captured CGRect. And that works.

But it seems horribly hacky and fraught with peril. This can't really be the right way to do this. (Can it?) skram's answer below seems so straightforward, but doesn't work for me when the app reloads.


Solution

  • Thanks to all who contributed answers! The sum of them all led me to the following:

    The trouble seems to have been that the bounds CGRect was being reset after loading the transform from preferences at startup, but not when updating the preferences while modifying in real time.

    I think there are two solutions. One would be to first load the preferences from layoutSubviews instead of from viewDidLoad. Nothing seems to happen to bounds after layoutSubviews is called.

    For other reasons in my app, however, it's more convenient to load the preferences from the view controller's viewDidLoad. So the solution I'm using is this:

    // UserTransformableView.h
    @interface UserTransformableView : UIView {
        CGRect defaultBounds;
    }
    
    // UserTransformableView.m
    - (id)initWithCoder:(NSCoder *)aDecoder {
        self = [super initWithCoder:aDecoder];
        if( self ) {
            defaultBounds = self.bounds;
        }
        return self;
    }
    
    - (void)layoutSubviews {
        self.bounds = defaultBounds;
    }