如何通过滑动和/或拖动来交换UIButton位置?

时间:2009-08-17 05:37:32

标签: iphone

我正在编写一个程序,我将UIButtons排列在一个正方形中。在NIB中。我使用“Touch Up Inside”事件,通过点击一个然后另一个来交换按钮。

我想通过向另一个方向滑动一个并将一个拖到另一个的顶部来交换它们。我一直无法弄清楚如何做到这一点。我已经在Apple文档中查了好几周了,但我真的不知道如何理解它。

有人可以告诉我我需要为我的代码做什么吗?

这是我的代码:

#import "squareViewController.h"
static UIButton *matrix[2][2];
static int firstButtonRow, firstButtonColumn, secondButtonRow, secondButtonColumn; 
static BOOL isFirstTouch = YES;
static  CGPoint gestureStartPoint;
@implementation squareViewController
@synthesize diamond;
@synthesize heart;
@synthesize spade;
@synthesize club;

- (void)viewDidLoad {


    matrix[0][0] = [diamond retain]; 
    matrix[0][1] = [heart retain]; 
    matrix[1][0] = [spade retain]; 
    matrix[1][1] = [club retain]; 

}   

- (void)ButtonTapped:(id)sender{
    int row = 0, column = 0; 
    for(row = 0; row < 2; row++){
        for(column = 0; column < 2; column++){
            if (matrix[row][column] == sender){ 
                if (isFirstTouch == YES){ 
                    firstButtonRow = row; 
                    firstButtonColumn = column; 
                    isFirstTouch = NO;  
                    return; 

                }
                else{
                    secondButtonRow = row; 
                    secondButtonColumn = column; 
                    [self SwapButtons: firstButtonRow: 
                    firstButtonColumn: 
                      secondButtonRow: 
                     secondButtonColumn]; 
                    isFirstTouch = YES;     
                    return; 



                }
            }   

        }
    }
}

- (void)ButtonSwiped:(id)sender {

    //  ?????

}

- (void)ButtonDragged:(id)sender {

    //  ?????

}

- (void)SwapButtons:(int)firstRow: (int)firstColumn: (int)secondRow: (int)secondColumn{
    UIButton *tempButton = [[[UIButton alloc] init] retain]; // allocate memory for tempButton
    UIButton *tempButtonOrig = tempButton;  // mirror tempButton to preserve adderess for release; 
    [UIView beginAnimations:@"main" context:nil];  
    tempButton.frame = matrix[firstRow][firstColumn].frame;
    matrix[firstRow][firstColumn].frame 
    = matrix[secondRow][secondColumn].frame;  
    matrix[secondRow][secondColumn].frame = tempButton.frame;  
    tempButton = matrix[firstRow][firstColumn];  
    matrix[firstRow][firstColumn] 
    = matrix[secondRow][secondColumn];  
    matrix[secondRow][secondColumn] = tempButton;  
    [tempButtonOrig release];       
    [UIView setAnimationDelegate:self]; 
    [UIView commitAnimations];      
}

1 个答案:

答案 0 :(得分:1)

不会为您处理滑动和拖动等手势;你几乎必须自己做这项工作。在我的应用程序中,我已经创建了一个UIView子类来执行此操作。您需要覆盖以下内容:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event

关于主题herehere的一些随机教程。