2013-08-02 49 views
0

我有幾個UIImageViews包含在UIView中。我的想法是當一個UIImageView被觸動時,UIView可以知道哪個人通過代表被觸摸。
這裏是我的代碼
MyImageView.h如何將UIImageView代理分配給其超級UIView,以便它可以知道哪個UIImageView被觸摸

@protocol MyImageViewDelegate 
    -(void)toucheDelegate:(id)sender; 
@end 

@interface MyImageView:UIImageView{ 
    id<MyImageViewDelegate> delegate; 
} 

@property(assign) id<MyImageViewDelegate> delegate; 
@end 

MyImageView.h

@implementation MyImageView 
@synthesize delegate 

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ 
    [self.delegate touchDelegate:self]; 
} 

MyView.m

-(void)functionA{ 
    for(int i=0;i<4;i++){ 
    MyImageView *imageView=[[MyImageView alloc] init]; 
    imageView.delegate=self; //Here it gives a warning saying Assigning to 'id<MyImageViewDelegate>' from incompatible type 'MyView *' 
    [self addSubview:imageView]; 
    [imageView release]; 
    } 
} 

-(void)touchDelegate:(id)sender{ 
    NSLog(@"in superview"); 
} 

唯一的例外是無法識別的seletor發送到實例0x7526c30。這是什麼意思?
我是新來的目標c,我不是很清楚這個代表事情或我在代碼塊中提到的警告。有什麼問題?任何建議?

+0

在你的MyView.h文件中確保你有這個:MyView:WhatYoureInheritingFrom JeffRegan

+0

什麼是完整的「無法識別的選擇器」錯誤信息? –

+0

默認情況下,UIImageview無法接受水龍頭。它的userInteractionEnabled設置爲NO。您可以將其更改爲「是」並嘗試。 – felix

回答

1

可以實現這樣

創建,然後圖像能夠通過userInteraction然後[imageView setUserInteractionEnabled:YES]添加標籤,並給UITapGestureRecognizer有選擇這就是你需要鬥。

for(int i=0;i<4;i++){ 
    MyImageView *imageView=[[MyImageView alloc] init]; 
    [imageView setUserInteractionEnabled:YES]; 
    [self.view addSubview:imageView]; 
    [self.imageView setUserInteractionEnabled:YES]; 
    [self.imageView setImage:[UIImage imageNamed:@"delete.png"]]; 
    [self.imageView setTag:i]; 
    UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imgTouchUp:)]; 
    tapped.numberOfTapsRequired = 1; 
    [self.imageView addGestureRecognizer:tapped]; 
} 

然後在選擇器識別UIImaged由它們各自的標籤如波紋管示出,其可以發現錄音。

-(void) imgTouchUp:(id)sender { 
    UITapGestureRecognizer *gesture = (UITapGestureRecognizer *) sender; 
    NSLog(@"Taped Image tag is %d", gesture.view.tag); 
} 

您還可以找到各種手勢。

  1. UITapGestureRecognizer
  2. UIPinchGestureRecognizer
  3. UIRotationGestureRecognizer
  4. UISwipeGestureRecognizer
  5. UIPanGestureRecognizer
  6. UILongPressGestureRecognizer
+0

這看起來比實現touchesBegan好得多。但是,如果我想移動觸摸的圖像視圖,我仍然需要在imgTouchUp中編寫代碼,就像我在touch中移動的那樣移動了嗎? – Violet

+0

如果我想通過使用UIGestureRecognizer在觸摸開始點和結束點處做點什麼? – Violet

+0

@Violet我已經更新了我的回答看看它。 – Ayush