我有一个背景图像(imageView - 标记 0),它已由几个标记图像子视图(imgView - 标记 1 - ?)填充。我在主背景图像中添加了一个点击识别器,并且还尝试了子视图。我可以通过点击进入后台点击识别程序,但无法识别已点击哪个子视图。
将点击识别器添加到背景(在 View did Load 期间):
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)];
[imageView addGestureRecognizer:singleTap];
[imageView setUserInteractionEnabled:YES];
在加载时将点击识别器添加到每个子视图:
- (void) showPics{ // display previously stored pictures
NSString *PictureName;
NSNumber *x;
NSNumber *y;
UIImage *viewImage;
tag = 1; // NSInteger declared in .h - background tag is zero
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)];
NSLog(@"reading from picFile: %@",self.picFile);
if ([[NSFileManager defaultManager] fileExistsAtPath:self.picFile]){
NSLog(@"FILE Found");
NSMutableArray *picData;
picData = [[NSMutableArray alloc] initWithContentsOfFile:self.picFile];
int count = picData.count/3;
NSLog(@"Count: %d",count);
// set up picture path before cycling through array
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// cycle to load pictures from file and place on background image
for(int i = 0; i < count; i++) {
PictureName = [picData objectAtIndex:i * 3];
NSString *showPic=[documentsDirectory stringByAppendingPathComponent:PictureName];
if ([[NSFileManager defaultManager] fileExistsAtPath:showPic]){
NSLog(@"Loading: %@",PictureName);
}else{
NSLog(@"Picture Does Not Exist");
}
x = [picData objectAtIndex:i * 3 + 1]; // x coord
y = [picData objectAtIndex:i * 3 + 2]; // y coord
viewImage = [UIImage imageWithContentsOfFile:showPic];
// find center of displayed image and place picture there
imgView = [[[UIImageView alloc] initWithFrame:CGRectMake([x floatValue] - 225,[y floatValue] - 172.5, 450, 345)] autorelease];
[imgView setImage:viewImage];
[imgView setContentMode:UIViewContentModeCenter];
[imgView addGestureRecognizer:singleTap];
[imgView setUserInteractionEnabled:YES];
imgView.tag = tag;
[imageView addSubview:imgView];
tag++;
NSLog(@"Tag: %d",tag);
}
[picData release];
}else{
NSLog(@"Did not find File");
}
}
在任何地方点击调用的例程:
- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)sender{
NSLog(@"singleTapGestureCaptured - SUBVIEWS: %d", [imageView.subviews count]);
NSLog(@"TAG: %d",sender.view.tag);
}
这正确地给了我子视图的数量,但除非我点击最后添加的子视图,否则总是返回“TAG:0”。我需要知道的是访问被点击子视图的标签的正确格式,以便我可以使其处于活动状态并移动它,或者关于如何执行此操作的任何其他建议。