0

我创建了简单UIScrollView的图像。每次按下图像时,我都想更改该图像,我该怎么做?

我创建它并用图像UIScrollView初始化它。NSMutableArray

      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++)
{
        UIImageView *imageV = [UIImageView alloc];
        [imageV setImage:[images objectAtIndex:i]];
        [myScroll addSubview:imageV];
        [imageV release];
}


    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget: self action:@selector (changeImg:)];
    [myScroll addGestureRecognizer: singleTap];

以及我在卷轴上被触摸的地方的感触:

- (void) singleTapGestureCaptured:(UITapGesturerecongnizer *) gesture
{
    CGPoint touch = [gesture locationInView:myScroll];

}

通过触摸项目的 X,Y 我知道选择了什么图像

在这里,我需要更改例如 myScroll 的第一张图片...我该怎么做?

4

3 回答 3

1

添加UITapGestureRecognizerUIImageView设置其userInractionEnabled: YES默认NOUIImageView.

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++)
{
    //In your question you didn't set `imageView` frame so correct it
    UIImageView *imageV = [[UIImageView alloc]initWithFrame:yourFrame];
    [imageV setImage:[images objectAtIndex:i]];
    [imageV setUserInteractionEnabled:YES];
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget: self action:@selector (changeImg:)];
    [imageV addGestureRecognizer: singleTap];
    [myScroll addSubview:imageV];
    [imageV release];
}

成功添加所有内容后imageView,您可以像这样单击它们:-

-(void)changeImg:(id)sender
 {
     UIGestureRecognizer *recognizer = (UIGestureRecognizer*)sender;
     UIImageView *imageView = (UIImageView *)recognizer.view;
     [imageView setImage:[UIImage imageNamed:@"anyImage.png"]];
 }
于 2012-09-22T12:25:44.137 回答
1

您的应用程序将崩溃,因为您正在访问索引 3,但索引 3 处没有任何对象。

UIScrollView *myScroll = [[UIScrollView alloc] initWithFrame: CGRectMake (0,100,200,30)];
NSMutableArray = *images = [NSMutableArray alloc] initWithObjects: img1,img2,img3,nil];
[myScroll addSubview:[images objectAtIndex:0];
[myScroll addSubview:[images objectAtIndex:1];
[myScroll addSubview:[images objectAtIndex:2];  

现在您可以使用 tagValue 访问图像视图

-(void)changeImg :(UIGestureRecognizer*)recog
{
    UIScrollView *scroll = (UIScrollView*)recog.view;
    CGPoint point = scroll.contentOffset;
    int imagetag = (point.y/scroll.frame.size.height);

    UIImageView *image=(UIImageView*)[[scroll subviews] objectAtIndex:imagetag];
    NSLog(@"Image tag = %d",image.tag);

    image.image=[UIImage imageNamed:@"Icon-72.png"];
}
于 2012-09-22T12:18:00.843 回答
0

一个简单的实现将是,如果您使用自定义按钮并在其 IBAction 上更改其图像。您仍然可以将 Gesture 添加到您的 UIImageView 和

if(recognizer.state == UIGestureRecognizerStateBegan)

您可以在运行时更改图像。我希望这有帮助。干杯!!

于 2012-09-22T12:18:22.080 回答