我正在构建一个 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/