多个UIImageView上的手势识别器

时间:2013-01-05 17:02:13

标签: objective-c uiimageview uigesturerecognizer

我在同一个ViewController中有10个UIImageViews,这些图像中的每一个都需要用Gesture Recognizer控制;这是我的简单代码:

- (void)viewDidLoad {

   UIImageView *image1 = // image init
   UIImageView *image2 = // image init
   ...

    UIRotationGestureRecognizer *rotationGesture1 = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotatePiece:)];
    UIRotationGestureRecognizer *rotationGesture2 = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotatePiece:)];
    ...
    ...
    UIRotationGestureRecognizer *rotationGesture10 = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotatePiece:)];

    [image1 addGestureRecognizer:rotationGesture1];
    [image2 addGestureRecognizer:rotationGesture2];
    ...
    ...
    [image10 addGestureRecognizer:rotationGesture10];
}

- (void)rotatePiece:(UIRotationGestureRecognizer *)gestureRecognizer {
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
        [gestureRecognizer view].transform = CGAffineTransformRotate([[gestureRecognizer view] transform], [gestureRecognizer rotation]);
        [gestureRecognizer setRotation:0];
    }
}

好吧,好吧,每个图像都旋转了,但是我需要为UIPanGestureRecognizer和UIPinchGestureRecognizer编写类似的代码,每个UIImageView的obv:这是正确的方法,还是有一个更简单的方法来避免像这样的“冗余”代码?谢谢!

1 个答案:

答案 0 :(得分:2)

这是一个可能的解决方案。制作一个类似的方法:

- (void)addRotationGestureForImage:(UIImageView *)image
{
    UIRotationGestureRecognizer *gesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotatePiece:)];
    gesture.delegate = self;
    [image addGestureRecognizer:gesture];
}

然后在你的viewDidLoad方法中创建一个图像视图数组并循环调用这个方法,如下所示:

NSArray *imageViewArray = [NSArray arrayWithObjects:image1,image2,image3,nil];
for(UIImageView *img in imageViewArray) {
    [self addRotationGestureForImage:img];
}
相关问题