将UISwipeGestureRecognizer添加到由数组生成的UIimageView中

时间:2014-07-24 16:06:02

标签: ios objective-c arrays uiimageview uiswipegesturerecognizer

代码:

标题文件:

@interface game : UIViewController
{

    UIImageView *anh[8][8];

}

-(void)SwipeToMove:(id)sender;

@end

实施档案:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UISwipeGestureRecognizer *move = [[UISwipeGestureRecognizer    alloc]initWithTarget:self action:@selector(SwipeToMove:)];
   [move setDirection:(UISwipeGestureRecognizerDirectionUp)];

    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {

            anh[i][j]=[[UIImageView alloc] initWithFrame:CGRectMake(0+40*i,200 + 40*j,40,40)];

            anh[i][j].userInteractionEnabled = YES;

            [self.view addSubview:anh[i][j]];

            anh[i][j].image = [UIImage imageNamed:@"Earth.png"];

            [anh[i][j] addGestureRecognizer:move];

       }
   }

}

-(void)SwipeToMove:(id)sender{

    NSLog(@"ok");
}

UIImageView按预期工作,但UISwipeGestureRecognizer无效。然后,我尝试了这个:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIImageView *image1 = [[UIImageView alloc]initWithFrame:CGRectMake(100,50,40,40)];
    label1.image = [UIImage imageNamed:@"Ceres.png"];
    [self.view addSubview:image1];
    image1.userInteractionEnabled = YES;
    image1.image = [UIImage imageNamed:@"Earth.png"];

    UISwipeGestureRecognizer *move = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(SwipeToMove:)];
   [move setDirection:(UISwipeGestureRecognizerDirectionUp)];

    [image1 addGestureRecognizer:move];



-(void)SwipeToMove:(id)sender{

    NSLog(@"OK");

}

它正在运行,但我需要一组UIImageView来制作我的应用。请帮帮我。

2 个答案:

答案 0 :(得分:0)

您的代码只创建一个手势识别器,但您尝试添加许多图像视图。您需要在循环内创建手势识别器,以便为每个图像视图创建一个新的手势识别器。

 (void)viewDidLoad
{
    [super viewDidLoad];

    for (int i = 0; i < 8; i++) {
        for (int j = 0; j < 8; j++) {
            UISwipeGestureRecognizer *move = [[UISwipeGestureRecognizer    alloc]initWithTarget:self action:@selector(SwipeToMove:)];
            [move setDirection:(UISwipeGestureRecognizerDirectionUp)];
            anh[i][j]=[[UIImageView alloc] initWithFrame:CGRectMake(0+40*i,200 + 40*j,40,40)];

            anh[i][j].userInteractionEnabled = YES;

            [self.view addSubview:anh[i][j]];

            anh[i][j].image = [UIImage imageNamed:@"Earth.png"];

            [anh[i][j] addGestureRecognizer:move];

       }
   }

}

答案 1 :(得分:0)

您正在为不同的图像添加相同的手势识别器,因此我只需要最后一个用于理解,因为您刚刚创建了一个。在循环中创建一个aux识别器,如aux var,并为每个UIImageView提供一个标签,这样您就可以访问该标签并区分每个图像中的每次滑动,当它在您的应用中发生时。它应该工作。但基本上是:

for (....){
   // create aux gesture recognizer and assign it to the UIImageView
}

希望它有所帮助。