2014-07-24 113 views
-1
做出

代碼:添加UISwipeGestureRecognizer到的UIImageView通過陣列

頭文件

@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秒的陣列,使我的應用程序。請幫幫我。

回答

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]; 

     } 
    } 

} 
+0

非常感謝您的回答。我會嘗試,但我有一個問題。在這種情況下,我不需要一個UISwipeGestureRecognizer數組? –

+0

@DangNguyenHuu,不,你不需要一組手勢識別器,因爲每個視圖都有自己的。如果你想知道哪個視圖被刷過,你可以從手勢識別器的視圖屬性中獲取。 – rdelmar

+0

謝謝你的評論。你一直在幫助很大。 –

0

您添加相同手勢識別所有的時間,以不同的圖像,因此將需要剛剛過去的一個我的理解,因爲你剛纔創建一個。在循環內創建一個類似aux的輔助識別器,併爲每個UIImageView提供一個標籤,這樣您就可以訪問該標籤並區分每個圖像中的每一次滑動,而這種情況發生在您的應用中。它應該工作。但基本上:

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

希望它有幫助。

+0

非常感謝您的回答。 –