我创建了具有图片的简单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的第一张图片......我该怎么做?
答案 0 :(得分: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"];
}
答案 1 :(得分:1)
在UITapGestureRecognizer
上添加UIImageView
并默认为userInractionEnabled:
设置YES
NO
UIImageView
。
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"]];
}
答案 2 :(得分:0)
一个简单的实现将是,如果你使用自定义按钮并在其IBAction上更改其图像..仍然你可以添加Gesture到你的UIImageView和
if(recognizer.state == UIGestureRecognizerStateBegan)
您可以在运行时更改图像。 我希望这有帮助。干杯!!