从NSMutablearray显示图像视图后,touchmove无法正常工作

时间:2013-02-19 13:27:55

标签: ios objective-c uiimageview nsmutablearray touchesbegan

我正在开发一个项目,我使用UIImageView动态创建NSMutableArray

这个代码是:

for (int i = 0; i < index ; i++) {
    image_name= [NSString stringWithFormat:@"%@%dpng.png",[string_values objectAtIndex:0],i+1];

    UIImageView *tempImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:image_name]];

    tempImageView.userInteractionEnabled = YES;
    CGSize size2=tempImageView.image.size;
    int width2=size2.width/2;
    int height2 =size2.height/2;
    tempImageView.frame = CGRectMake(xvalue,yvalue,width2,height2);  

    [myArray addObject:tempImageView];
}

之后我添加了子视图,使用以下代码在屏幕上显示:

for(int i=0;i<[myArray count];i++) {
    [self.view addSubview:[myArray objectAtIndex:i]];
}

以上所有代码都根据需要运行良好。现在对于touchesBegan方法,我正在做这个代码:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    printf("the touch is fired");
    for(int i=0;i<[myArray count];i++) {
        [self.view addSubview:[myArray objectAtIndex:i]];
        touchStart = [[touches anyObject] locationInView:[myArray objectAtIndex:i]];
    }
}

在打印touchesBegan方法的第一行之后,当调用touchesBegan方法时,应用程序崩溃。

我在这里遇到困难,也经历过很多问题/答案,但找不到合适的解决方案。任何帮助将不胜感激。感谢好回复

1 个答案:

答案 0 :(得分:0)

要使您的图像视图可拖动,

1)删除所有 - (void)触摸方法

2)在创建UIImageView * tempImageView(循环)

后立即添加这两行
 UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleDrag:)];
[tempImageView addGestureRecognizer:panRecognizer];

3)然后,在视图controller.m文件中的某处添加此方法

-(void) handleDrag:(UIPanGestureRecognizer *) panGesture{
CGPoint transition = [panGesture translationInView:self.view];
panGesture.view.center = CGPointMake(panGesture.view.center.x + transition.x, panGesture.view.center.y +transition.y);
[panGesture setTranslation:CGPointMake(0,0) inView:self.view];}