Animating UIView frame.origin
Asked Answered
A

3

10

I have seen some sample code online regarding a simple UIView slide-in or slide-out. It makes sense to have a UIView start with its coordinates off the screen (negative) and then the animation parameter simply changes the UIView's frame. So first question is: does this provide the most obvious method?

However, in my code, the frame origin is not assignable. I get the Xcode error for that line that says as much.

I simply want to do something like this inside an animation:

self.viewPop.frame.origin.y=100;

Any help is appreciated.


UPDATE

I have solved this problem. The technique I discovered is to assign your view's frame to another CGRect, and make changes to that CGRect, then assign it back to the frame:

CGRect frame = self.moveView.frame;
frame.origin.x = newvalue.


[UIView animateWithDuration:2.0 animations:^{ 

    self.moveView.frame = frame;

}];
Analcite answered 12/6, 2011 at 23:8 Comment(1)
Move your solution into an answer, then mark it as the correct one.Morbidezza
A
12

I have solved this problem. The technique I discovered is to assign your view's frame to another CGRect, and make changes to that CGRect, then assign it back to the frame:

CGRect frame = self.moveView.frame;
frame.origin.x = newvalue.


[UIView animateWithDuration:2.0 animations:^{ 

    self.moveView.frame = frame;

}];
Analcite answered 13/6, 2011 at 13:39 Comment(0)
L
1

FWIW, it's nice to have a UIView category around for this type of thing:

@interface UIView (JCUtilities)

@property (nonatomic, assign) CGFloat frameX;

-(CGFloat)frameX;
-(void)setFrameX:(CGFloat)newX;

@end

@implementation UIView (JCUtilities)

- (CGFloat)frameX {
    return self.frame.origin.x;
}

- (void)setFrameX:(CGFloat)newX {
    self.frame = CGRectMake(newX, self.frame.origin.y,
                            self.frame.size.width, self.frame.size.height);
}
Laing answered 22/3, 2013 at 15:49 Comment(0)
P
0

The answer is correct, but if you want to understand why it works, you need to understand the difference between value and reference types. CGRect is a value type (like a struct, unlike a class which is a reference type).

Value types are immutable, meaning that if you assign a new value to one of its properties (Swift won't allow you to do this), you won't mutate the original value, but it will give you a copy of the item with the updated value.

More on this here Swift structs are immutable, so how come I can change them?

Prizewinner answered 3/5, 2024 at 4:28 Comment(1)
Not that this question was from 2011 long before Swift existed.Analcite

© 2022 - 2025 — McMap. All rights reserved.