根据手势重新排列UIIviews

时间:2012-12-01 23:18:47

标签: iphone objective-c ios xcode uiview

我正在一个UIViewController中构建一个在3x3矩阵中有多个UIViews的iphone应用程序(总共9个UIViews)。我试图找到一种方法让用户将一个视图移动到矩阵中的某个位置,然后相应地重新排列其余视图。想想当你将跳板上的应用程序拖到另一个地方时,所有其他图标都会相应地排列。

实现类似目标的最佳方式是什么?

2 个答案:

答案 0 :(得分:1)

使用UIPanGestureRecognizer,使用translationInView调整您要拖动的项目的坐标。有关手势识别器的讨论,请参阅Event Handling Guide for iOS

当你放手(即手势结束)时,你可以使用UIView类方法animateWithDuration来动画将各种项目移动到最终位置。

因此,在viewDidLoad中,您可能会执行以下操作(假设您在名为arrayOfViews的数组中有九个控件):

for (UIView *subview in self.arrayOfViews)
{
    UIPanGestureRecognizer *gesture = [[UIPanGestureRecognizer alloc] initWithTarget:self  
                                                                              action:@selector(movePiece:)];
    [subview addGestureRecognizer:gesture];
}

然后您的手势识别器处理程序可能如下所示:

- (void)movePiece:(UIPanGestureRecognizer *)gesture
{
    static CGPoint originalCenter;

    if (gesture.state == UIGestureRecognizerStateBegan)
    {
        originalCenter = gesture.view.center;
    }
    else if (gesture.state == UIGestureRecognizerStateChanged)
    {
        CGPoint translation = [gesture translationInView:self.view];

        gesture.view.center = CGPointMake(originalCenter.x + translation.x, originalCenter.y + translation.y);
    }
    else if (gesture.state == UIGestureRecognizerStateEnded)
    {
        [UIView animateWithDuration:0.25
                         animations:^{

            // move your views to their final resting places here
        }];
    }
}

这可能是拖拽周围控件的原因。

答案 1 :(得分:0)

如果您正在为iOS 6开发,请务必查看UICollectionView课程。如果您在学习曲线不应太陡之前处理过表格视图。您可以免费获得重新排列和所有动画。

相关问题