我建议
使用带有参数的手势处理程序(以防您将手势添加到多个视图);
确保相关视图已userInteractionEnabled
打开。
delegate
除非您正在实现其中一种方法,否则您不需要设置手势UIGestureRecognizerDelegate
。
因此,配置可能如下所示:
templateView.userInteractionEnabled = YES;
swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
[templateView addGestureRecognizer:swipeRight];
swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
[templateView addGestureRecognizer:swipeLeft];
然后手势处理程序可能如下所示:
- (void)handleSwipe:(UISwipeGestureRecognizer *)gesture
{
CGRect frame = self.gridView.frame;
// I don't know how far you want to move the grid view.
// This moves it off screen.
// Adjust this to move it the appropriate amount for your desired UI
if (gesture.direction == UISwipeGestureRecognizerDirectionRight)
frame.origin.x += self.view.bounds.size.width;
else if (gesture.direction == UISwipeGestureRecognizerDirectionLeft)
frame.origin.x -= self.view.bounds.size.width;
else
NSLog(@"Unrecognized swipe direction");
// Now animate the changing of the frame
[UIView animateWithDuration:0.5
animations:^{
self.gridView.frame = frame;
}];
}
请注意,如果您使用自动布局并且视图是由约束而不是 定义的translatesAutoresizingMaskIntoConstraints
,则此处理程序代码必须适当更改。但希望这能给你基本的想法。