0

同じ ViewController に 10 個の UIImageView があり、これらの各画像を 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: これは正しい方法ですか、それともこのような「冗長な」コードを回避するためのより簡単な方法がありますか? ありがとう!

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 に答える