iphone - 根据手势重新排列 UIIview

标签 iphone objective-c ios xcode uiview

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

完成类似任务的最佳方法是什么?

最佳答案

使用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
        }];
    }
}

这就是拖动控件的大概样子。

关于iphone - 根据手势重新排列 UIIview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13664757/

相关文章:

iphone - 使用 AVAssetReader 和 ARC 绘制波形

iphone - 通过 "propertyname"访问属性与 objective-c 中的 "self.propertyname"之间的区别?

ios - index 0 beyond bounds for empty array - 找到数组但如何修复?

objective-c - 使一个变量依赖于另一个变量

ios - 删除字符串中所有两次重复字符的方法

javascript - 确认 UIWebView 中的 Javascript 行为

ios - touchesBegan 之后调用的 viewDidLayoutSubviews - 一次又一次

iphone - 如果我释放,我将无法访问,如果我保留,我将泄漏

objective-c - DEBUG宏在哪里定义的?

ios - NativeScript 和带有 XIB 的 iOS 动态框架