冒着在没有看到应用全貌的情况下提出建议的风险,为什么不使用自定义 UIButton 而不是 UIImageViews 呢?使用 UIButton,您可以设置操作并传递发送者 ID,您可以从中轻松访问标签并从数组中提取数据。
UIButton *button = [[UIImageView alloc] initWithFrame:CGRectMake(10, i*100 + i*15, 300, 100)];
button.backgroundColor = [UIColor blueColor];
button.tag = i;
[button addTarget:self action:@selector(touchDown:) controlEvent:UIControlEventTouchDown];
在 touchDown: 方法中,您只需将 sender 强制转换为 UIButton 即可访问标签
- (void)touchDown:(id)sender
{
UIButton* button = (UIButton*)sender;
switch(button.tag)
{
case TAG1:
break;
//etc
}
}
或者看看这个
UIScrollView *myScroll = [[UIScrollView alloc] initWithFrame: CGRectMake (0,100,200,30)];
NSMutableArray = *images = [NSMutableArray alloc] initWithObjects: img1,img2,img3,nil];
for (int i=0; i<3; i++)
{
// set `imageView` frame
UIImageView *imageV = [[UIImageView alloc]initWithFrame:yourFrame];
[imageV setImage:[images objectAtIndex:i]];
[imageV setUserInteractionEnabled:YES];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget: self action:@selector (getTag:)];
[imageV addGestureRecognizer: singleTap];
[myScroll addSubview:imageV];
}
根据需要为图像设置标签
成功添加所有 imageView 后,您可以像这样点击它们:-
-(void)getTag:(id)sender
{
UIGestureRecognizer *recognizer = (UIGestureRecognizer*)sender;
UIImageView *imageView = (UIImageView *)recognizer.view;
if(imageView.image.tag==1)
{
[imageView setImage:[UIImage imageNamed:@"anyImage.png"]];
}
}