如何将UIImageView委托分配给它的超级UIView,以便它可以知道触摸了哪个UIImageView

时间:2013-08-02 21:07:08

标签: objective-c

我有几个由UIView包含的UIImageViews。我的想法是当触摸UIImageView时,UIView可以通过委托知道哪一个被触摸 这是我的代码
MyImageView.h

@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的新手,我不太清楚这个委托的事情或我在代码块中提到的警告。有什么问题?有什么建议吗?

1 个答案:

答案 0 :(得分: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