0

我在同一个 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];
    }
}

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

4

1 回答 1

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];
}
于 2013-01-07T11:41:06.247 回答