交换位置UIViews Xcode

时间:2013-07-05 21:56:21

标签: objective-c xcode uiview uiimageview swap

我想知道如何在Xcode中相互接触时交换两个UIImageViews的位置。

示例:

if (CGRectIntersectsRect(view1.frame, view2.frame)) {
   [UIView animateWithDuration:0.2 animations:^{
     CGRect view1Frame = view1.frame;
     view1.frame = view2.frame;
     view2.frame = view1Frame;
   }];
}

不幸的是,这不起作用,因为变量每次都会记住旧位置。 你能帮我解决这个问题吗?

5 个答案:

答案 0 :(得分:0)

这可能有助于指向CGRect结构

的指针
CGRect *view1Frame

应替换为:

CGRect view1Frame = view1.frame;

我不想更深入地了解Structs和Objects,因为它们之间的线条会模糊:D但是在这种情况下你只需要使用CGRect而不使用指针。您甚至可以从xcode获得警告......

感谢问候

答案 1 :(得分:0)

您可以从图层的表示层获取当前位置。

CGPoint currentPos1 = [view1.layer.presentationLayer position];
NSLog(@"%f %f",currentPos1.x,currentPos1.y);
CGPoint currentPos2 = [view2.layer.presentationLayer position];
NSLog(@"%f %f",currentPos2.x,currentPos2.y);

之后你可以动画来交换它们......

答案 2 :(得分:0)

我怀疑你是两次调用这个方法,因为它们两次重叠,动画只是自我撤销。试试这个:

BOOL animationDone = NO;

if (CGRectIntersectsRect(view1.frame, view2.frame) && !animationDone) { 
    [UIView animateWithDuration:0.2 animations:^{
     CGRect view1Frame = view1.frame;
     view1.frame = view2.frame;
     view2.frame = view1Frame;
     animationDone = YES;
    }];
}

答案 3 :(得分:0)

尝试以下方法:

CGRect view1Frame = view1.frame;
CGRect view2Frame = view2.frame;

if (CGRectIntersectsRect(view1.frame, view2.frame)) {
   [UIView animateWithDuration:0.2 animations:^{
     view1.frame = view2Frame;
     view2.frame = view1Frame;
   }];
}

我认为这应该可行我没有测试它但通常这应该没问题... 请告诉我......

另外:如果你想直接更改一个块内的变量,使它们在离开块后有其他值,你需要用__block声明它们(有关块的详细信息,我建议使用apple docu http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/Blocks/Articles/bxVariables.html#//apple_ref/doc/uid/TP40007502-CH6-SW6

问候

答案 4 :(得分:0)

您可以使用元组来执行此操作:)

(view1.frame, view2.frame) = (view2.frame, view1.frame)
相关问题