1

我有一个应用程序,用户点击一个按钮,该应用程序将实例化一个图像层(UIImageView)。我想这样做,以便用户可以移动选定的图像层,无论他们点击什么。在这里阅读了一些主题后,我了解到我可以使用UIPanGestureRecognizer来移动选定的图像层。

- (IBAction)buttonClicked:(id)sender {
    imageview = [[UIImageView alloc] initWithFrame:CGRectMake(100, 0, 300, 22)];
    UIPanGestureRecognizer *imageviewGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(recognizePan:)];
    [imageviewGesture setMinimumNumberOfTouches:1];
    [imageviewGesture setMaximumNumberOfTouches:1];
    imageview.image = [UIImage imageNamed:@"pinimage.png"];
    [imageview addGestureRecognizer:imageviewGesture];
    [imageview setUserInteractionEnabled:YES];
    [self.view addSubview:imageview];
    NSUInteger currentag = [self UniqueTag]; // Assigning a unique integer
    imageview.tag = currentag;
}

- (void)recognizePan:(UIPanGestureRecognizer *)sender {
    [[[(UITapGestureRecognizer *)sender view] layer] removeAllAnimations];
    [self.view bringSubviewToFront:[(UIPanGestureRecognizer *)sender view]];
    CGPoint translatedPoint = [(UIPanGestureRecognizer *)sender translationInView:self.view];

    if([(UIPanGestureRecognizer *)sender state] == UIGestureRecognizerStateBegan) {     
        firstX = [[sender view] center].x;
        firstY = [[sender view] center].y;
    }

    translatedPoint = CGPointMake(firstX + translatedPoint.x,firstY + translatedPoint.y);
    [[sender view] setCenter:translatedPoint];
}

现在,我无法弄清楚当有多个图像层时如何将点击层放在前面。[self.view bringSubviewToFront:[(UIPanGestureRecognizer *)sender view]] 似乎没有效果。那么如何修改我的代码,以便应用程序将点击层带到顶部呢?

谢谢您的帮助。

4

1 回答 1

2

一个很好的方法是创建 UIImageView 的 CustomImageView 子类。您将 UIPanGestureRecognizer 附加到 CustomImageView 的每个实例,并将该实例设置为它的目标。然后手势触发的动作方法是在视图本身实现的,这样就可以用 来引用视图self

buttonClicked

    MyImageView* imageview = [[MyImageView alloc] initWithFrame:CGRectMake(100, 0, 300, 22)];
    UIPanGestureRecognizer *imageviewGesture = 
    [[UIPanGestureRecognizer alloc] initWithTarget:imageview 
                                            action:@selector(recognizePan:)];

CustomImageView.m

    - (void)recognizePan:(UIPanGestureRecognizer *)sender {
        [self.layer removeAllAnimations];
        [self.superview bringSubviewToFront:self];
        CGPoint translatedPoint = [sender translationInView:self];
        if([sender state] == UIGestureRecognizerStateBegan) {
            self.firstX = [self center].x;
            self.firstY = [self center].y;
        }
        translatedPoint = CGPointMake(self.firstX + translatedPoint.x,
                                      self.firstY + translatedPoint.y);
        [self setCenter:translatedPoint];
    }

更新

不直接思考 - 你当然可以从 viewController 中执行此操作,就像你正在做的那样,通过访问viewgestureRecongnizer 的属性。你的错误就在这里:

- (void)recognizePan:(UIPanGestureRecognizer *)sender {
     [[[(UITapGestureRecognizer *)sender view] layer] removeAllAnimations];

您正在将发件人类型从 更改UIPanGestureRecognizerUITapGestureRecognizer。事实上,您不需要sender在方法体中进行任何类型转换。

于 2013-04-14T01:16:29.653 回答