【问题标题】:touchmoved not working after displaying uiimageviews from NSMutable array从 NSMutablearray 显示图像视图后,touchmove 不起作用
【发布时间】:2013-02-19 13:27:55
【问题描述】:

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

代码如下:

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 方法的第一行之后立即崩溃。

我在这里遇到了困难,也经历了许多问题/答案,但找不到有效的解决方案。任何帮助将不胜感激。感谢您的好评

【问题讨论】:

  • 声明 myArray 为 strong 并在初始化时使用 self.myArray = [NSMutableArray array];
  • stacktrace 会很有帮助。
  • 不清楚你在touchesbegan函数里做什么?
  • 你能告诉你想在 touchesBegan 方法中做什么@Tahir Mehmood
  • @Vinu1991 实际上在绘制图像之后>>我想拖动它们所有这些都只使用一个图像并且当我通过 NSMutable 数组添加 5 个图像时,应用程序实际上在 touchesBegan 方法中崩溃获取坐标和比较是在 touchesMoved 和 touchesEnded 方法中完成的>>但应用程序在转到它们之前会崩溃

标签: ios objective-c uiimageview nsmutablearray touchesbegan


【解决方案1】:

为了使您的图像视图可拖动,

1) 删除所有 - (void)touches 方法

2) 在创建 UIImageView *tempImageView (in loop) 之后添加这两行

 UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleDrag:)];
[tempImageView addGestureRecognizer:panRecognizer];

3) 然后,将此方法添加到 view 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];}

【讨论】:

  • 我正在使用 touchesBegan ,touchesMoved,touchesEnded 方法>>以及使用这些方法的任何建议???
  • 我的建议是不要在代码中使用 touchesBegan ,touchesMoved,touchesEnded 来拖动图像视图。使用 GestureRecognizers 使您的代码非常清晰,这是推荐的方式。
  • 那么如何获取触摸坐标>>用户触摸uiimageview的位置>>
  • 你能清楚地告诉我你想做什么吗?我可以帮你
  • 我正在开发一个游戏,其中我在屏幕上随机显示五个 uiimageviews>> 我使用 uiimageview 数组来存储,然后通过迭代到整个数组我正在添加子视图>> 问题是 taht 之后绘制图像触摸功能没有执行>>实际上touchesBegan函数需要一个uiimage来识别每个元素的拖动>但在我的情况下我使用uiimage数组所以要给触摸函数执行什么>>它一切都很好对于单个图像???
猜你喜欢
  • 1970-01-01
  • 2019-03-18
  • 1970-01-01
  • 2020-09-19
  • 1970-01-01
  • 1970-01-01
  • 2013-06-23
  • 1970-01-01
  • 2010-10-08
相关资源
最近更新 更多