【问题标题】:Gesture recognizer on multiple UIImageView多个 UIImageView 上的手势识别器
【发布时间】:2013-01-05 17:02:13
【问题描述】:

我在同一个ViewController中有10个UIImageView,每一个都需要用一个手势识别器来控制;这是我的简单代码:

- (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 编写类似的代码:这是正确的方法,还是有更简单的方法来避免像这样的“冗余”代码?谢谢!

【问题讨论】:

  • 谢谢,也许我需要更多帮助来澄清这个问题..
  • 不,我真的不好笑,而不是拥有 image1、image2、image3 和 recongizer1、recognizer2、recognizer3,而是拥有一个图像数组和一个识别器数组,并在 for 循环中完成所有工作。这样您就可以任意更改查看次数等

标签: objective-c uiimageview uigesturerecognizer


【解决方案1】:

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

- (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];
}

【讨论】:

  • 不错的代码,但在代码 [image addGestureRecognizer:gesture]; Xcode 警告:“UIImage”没有可见的@interface 声明选择器“addGestureRecognizer”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多