简体   繁体   English

一次移动多个对象-iOS

[英]Move multiple objects at once - iOS

I have a view with about 10 objects on it, and I have set all individual tags for them. 我有一个带有大约10个对象的视图,并且为它们设置了所有单独的标签。 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. 我想将它们全部向上移动20点,以使其原始Y位置减去20,使用for循环并遍历每个标签。 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. 但这需要我给出X,Y,宽度和高度。 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? 所以我的问题是,如何找到所有对象的原始坐标并将X,W和H设置为原始坐标,而仅将Y向上移动?

Any tips would be greatly appreciated. 任何提示将非常感谢。

Thanks 谢谢

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;

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. 这样,您可以使用for-in语句并检查标记是否为您要移动的视图的标记,并且如果条件为true,则对视图应用仿射变换。 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. 使用视图的transform属性而不是直接修改框架将允许知道视图与其原始位置的确切偏移量。

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. 我假设在这里,您只使用从UIView继承的对象,例如UIButton,UILabel,UITextField等。您可以先将所有当前帧放入数组中,然后再将所有元素放入数组中。 That way, you can loop the second array, and for each elemnt, set Y to be array2[i]-20. 这样,您可以循环第二个数组,对于每个元素,将Y设置为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)];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM