0

我使用 UIBezierPath 实现了一个正方形绘制。为了移动同一个方块,我实现了一个 UILongPressGestureRecognizer 以便我可以检查方块是否被按下并在子视图中自由移动方块。

这是一些代码:

square.h

...
//square coordinates and size

static const float xPoint = 10;
static const float yPoint = 16;
static const float Width = 10;
static const float Height = 20;

//bezier BitMap context
static const float contextWidht = 300;
static const float contextHeigh = 300;
... 

square.m
...
-(void)build{

  UIBezierPath *squareDraw = [UIBezierPath bezierPathWithRect:CGRectMake(xPoint, yPoint, Width, Height)];
  UIGraphicsBeginImageContext(CGSizeMake(contextWidht, contextHeigh));

  // Graphic Context
  CGContextRef context = UIGraphicsGetCurrentContext();
  CGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);
  CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);

  [squareDraw fill];
  [squareDraw stroke];

  // Get image from Graphic Context
  UIImage *bezierImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  UIImageView *bezierImageView = [[UIImageView alloc]initWithImage:bezierImage];

  //subView 
  _frame = bezierImageView;
  [_frame setUserInteractionEnabled:YES];

  //Gesture Recognizer
  UILongPressGestureRecognizer *tapGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(tapHandler:)];
  tapGesture.delegate = (id)self;

  [_frame addGestureRecognizer:tapGesture];
  [self addSubview:_frame];

}

- (void)tapHandler:(UILongPressGestureRecognizer *) sender{

  sender.delegate = (id)_frame;
  CGPoint touchLocation = [sender locationInView:_frame];
  CGFloat xVariation, yVariation;
  ...

  case UIGestureRecognizerStateChanged:
    xVariation = [sender locationInView:_frame].x;
    yVariation = [sender locationInView:_frame].y;
    _frame.center = CGPointMake(xVariation, yVariation);        
  break;
  ....
}

似乎,在调试应用程序时(按下并移动 _frame),“UIGestureRecognizerStateChanged”被调用两次,并返回子视图和由 contextWidth 和 contextHeight 产生的一些点之间的交替点:

2013-07-22 14:55:00.327 bezier[10847:11603] xVariation: 22.000000
2013-07-22 14:55:00.329 bezier[10847:11603] yVariation: 28.000000
2013-07-22 14:55:00.330 bezier[10847:11603] xVariation: 150.000000 ----> ??
2013-07-22 14:55:00.330 bezier[10847:11603] yVariation: 150.000000 ----> ??
2013-07-22 14:55:00.332 bezier[10847:11603] xVariation: 29.000000
2013-07-22 14:55:00.332 bezier[10847:11603] yVariation: 28.000000

为什么会这样?

4

1 回答 1

0

UILongPressGestureRecognizer 总是连续发送数据。如果你只想要一个信号,你需要在你的委托中处理这个并观察状态。从文档中:

长按手势是连续的。当允许的手指数量 (numberOfTouchesRequired) 在指定的时间 (minimumPressDuration) 内被按下并且触摸没有超出允许的移动范围 (allowableMovement) 时,手势开始 (UIGestureRecognizerStateBegan)。每当手指移动时,手势识别器就会转换到 Change 状态,并在任何手指抬起时结束 (UIGestureRecognizerStateEnded)。

于 2013-07-23T08:23:37.667 回答