0

我已经阅读了许多教程来使用 touchesmoved 方法在屏幕上拖动图像,但其中大多数不适用于动态创建的图像视图

在我的项目中,我以编程方式创建了 5 个 UIImageview,

现在我希望用户可以将它们拖到屏幕上>>我也遵循这个答案 问题但一切都是徒劳的,到目前为止没有成功>

创建动态图像视图的代码是

for (int i = 0; i < index ; i++) 
{
UIImageView *imageView1 = [[UIImageView alloc] initWithImage:
[UIImageimageNamed:image_name]];        
self.imageView1.userInteractionEnabled = YES;
imageView1.frame = CGRectMake(xvalue, yvalue, 80.0f, 80.0f);
self.view.userInteractionEnabled = YES;
[self.view addSubview:imageView1];
}

提前感谢您的良好回复

4

2 回答 2

0

有很多方法可以解决这个问题。您可以在创建每个 UIImageView 时将 UIPanGestureRecognizer 添加到每个 UIImageView,也可以在 self 上使用 touchesBegan:、touchesMoved:(假设它是 UIViewController)并遍历每个 UIImageView 以查看其框架是否包含触摸点。

于 2013-02-14T12:43:28.430 回答
0

我对您创建 UIImageViews 的方式有些困惑,因为您使用的是 for 循环,但使用的是静态名称。因此,您可能有 15 个名称为“imageView1”的 UIImageView。但无论如何,如果您使用链接到的问题中的代码,这根本不重要。也许你把线弄乱了……这是正确的顺序。(如果它不起作用,请告诉我,以及你得到的错误)

//-(void)ViewDidLoad? {???? is this your function??
    int xvalue = 0;//?? not sure where you declared these
    int yvalue = 0;//?? not sure where you declared these
    for (int i = 0; i < index ; i++) {
        UIImageView *imageView1 = [[UIImageView alloc] initWithImage:
        [UIImageimageNamed:image_name]];        
        self.imageView1.userInteractionEnabled = YES;
        imageView1.frame = CGRectMake(xvalue, yvalue, 80.0f, 80.0f);
        self.view.userInteractionEnabled = YES;
        [self.view addSubview:imageView1];
    }

    self.elements=[myElements getElements];
    imagesElements = [[NSMutableArray alloc]init];
    for(ElemetsList *item in self.elements) {
            UIImageView *oneelement = [[UIImageView alloc] initWithImage:[UIImage imageNamed:item.imgElement]];
            oneelement.frame = CGRectMake(item.positionX, item.positionY, item.width, item.height);
            oneelement.userInteractionEnabled=YES;
            [imagesElements addObject:oneelement];
    }

    for(UIImageView *img in imagesElements) {
        [self.view addSubview:img];
    }
//}? End Function, whatever it may be...?

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];

    for(UIImageView *img in imagesElements) 
    {  
        if([self view] == img)
        {
            CGPoint location = [touch locationInView:self.view];
            img.center=location;
        }
    }
}

如果您只想在移动中对一张图像进行硬编码,请尝试以下操作:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    imageView1.center=[touch locationInView:self.view];
}
于 2013-02-14T12:43:35.523 回答