Question

I have a view with about 10 objects on it, and I have set all individual tags for them. I would like to move them all up by 20 points so their original Y position minus 20, using a for loop and iterating through each tag. I know I can do something like

[self.view viewWithTag:i].frame = CGRectMake(X, Y-20, W, H);;

but that requires me to give an X, Y, Width, and Height. So my question is, how can I find the original coordinates for all the objects and set the X, W, and H to the original and only move Y up?

Any tips would be greatly appreciated.

Thanks

Was it helpful?

Solution

Simply base the view's new frame on its current one:

UIView* view = [self.view viewWithTag:i];
CGRect frame = view.frame;
frame.origin.y -= 20;
view.frame = frame;

OTHER TIPS

Why not just apply the same tag to all the views that you want to move. That way you can use a for-in statement and check if the tag is that of the view you want to move and if the condition is true, apply an affine transform with to the view. Using the transform property of the view instead of directly modifying the frame will allow to know the exact offset of the view from its original position.

NSInteger myTag = 4;

for (UIView *view in self.view.subviews) {
    if (view.tag == myTag) {
        [view setTransform:CGAffineTransformMakeTranslation(0.0f, - 20.0f)];
    }
}

I might have an idea you can try. I'm assuming here you are only using objects that are inheriting from UIView, like UIButton, UILabel, UITextField etc. You could first put all current frames in an array, and then put all the elements in an array. That way, you can loop the second array, and for each elemnt, set Y to be array2[i]-20.

NSMutableArray *currentFrames = [[NSMutableArray alloc] init];
for(int i = 0; i<10; i++) //10 being the number of elements, assuming they have tags from 0 to 9
    [currentFrames addObject:[NSValue valueWithCGRect:[self.view viewWithTag:i].frame]];

for(int i = 0; i<currentFrames.count; i++)
{
    UIView *v = [self.view viewWithTag:i];
    [v setFrame:CGRectMake(v.frame.origin.x, v.frame.origin.y-20, v.frame.size.width, v.frame.size.height)];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top