与UIButton对象一起识别滑动方向



我需要识别滑动的方向,并知道视图中的哪个对象发送了它。我现在已经找到了解决方法,但它看起来既复杂又可怕,所以我怀疑有没有最简单的解决方案?我的变通方法:

  1. 我将识别器附加到视图中的每个UIButton对象
  2. 有一个指示灯显示在执行滑动时点击了哪个按钮
  3. 我必须检查这个指示器并滑动方向以做出正确的决定,应该移动哪个对象和方向

谢谢你的建议。

@合成滑动方向//显示滑动方向的标签@合成按钮编号//显示被点击按钮数量的标签-(无效)viewDidLoad{UIButton*button=[UIButtonWithType:UIButtonTypeRoundRect]//创建按钮[button setTitle:@"test1"forState:UIControlStateNormal];button.frame=CGRectMake(100,100,100);[button addTarget:self//添加选择器,它将更新被点击按钮的指示器,没有点击按钮就无法进行滑动操作:@selector(updateButtonNumber:)forControlEvents:UIControlEventTouchDown];[按钮设置标签:1];[self.view addSubview:button]//将按钮添加到视图[self-beginListenToScripps:button]//向方法发送按钮,该方法将为4个方向添加UISwipeGestureRecognizer/*第二个按钮的任务相同*/UIButton*button1=[UIButtonWithType:UIButtonTypeRoundRect];[button1 setTitle:@"test2"forState:UIControlStateNormal];button1.frame=CGRectMake(200、200、100、100);[button1 addTarget:self操作:@selector(updateButtonNumber:)forControlEvents:UIControlEventTouchDown];[button1 setTag:2];[self.view addSubview:button1];[self-beginListenToScripps:button1];}/*每当我们点击按钮(开始滑动)时,就会调用此方法,并且buttonNumber总是指向当前按钮*/-(void)updateButtonNumber:(UIButton*)发件人{self.buttonNumber.text=[NSString字符串WithFormat:@"%d",sender.tag];}/*方法接收UIButton并向其中添加识别器*/-(void)beginListenToScripps:(UIButton*)发件人{UISwipeGestureRecognizer*识别器;识别器=[[UISwipeGestureRecognizer alloc]initWithTarget:self-action:@selector(handleSwip:)];[识别器设置方向:(UISvipeGestureRecognizerDirectionRight)];[sender addGestureRecognizer:识别器];识别器=[[UISwipeGestureRecognizer alloc]initWithTarget:self-action:@selector(handleSwip:)];[识别器设置方向:(UISvipeGestureRecognizerDirectionLeft)];[sender addGestureRecognizer:识别器];识别器=[[UISwipeGestureRecognizer alloc]initWithTarget:self-action:@selector(handleSwip:)];[识别器设置方向:(UISvipeGestureRecognizerDirectionUp)];[sender addGestureRecognizer:识别器];识别器=[[UISwipeGestureRecognizer alloc]initWithTarget:self-action:@selector(handleSwip:)];[识别器设置方向:(UISvipeGestureRecognizerDirectionDown)];[sender addGestureRecognizer:识别器];}/*方法,该方法调用何时执行滑动并显示其执行方向*/-(无效)手柄擦除:(UISvipeGestureRecognizer*)识别器{int i=识别器方向;self.swipeDirection.text=[NSString字符串WithFormat:@"%d",i];}

我的想法是,

  1. 为UIButton注册touchUpoutside事件
  2. 当你把手指从按钮上移开时,它就会被击发
  3. 从touchesEnded方法中找到接触点,并存储在类级别的变量中
  4. 比较touchupoutside方法中的按钮框和触摸点,以找到移动方向

我认为你也可以把你的手势识别器放在self.view中,然后看看手势是否发生在有问题的控件上(显然,你想让你的按钮成为viewcontroller的ivar或属性,这样你就可以跟踪哪个是哪个),例如

CGPoint point = [sender locationInView:self.view];
if (CGRectContainsPoint(button1.frame, point))
// do whatever you want

这取决于您是否在UIGestureRecognizerStateBegan或UIGesture RecognizerstateEnded或两者都执行此逻辑。

更新:

顺便说一句,如果你正在检测你移动东西的方向,你也可以考虑使用UIPanGestureRecognizer,它在一个手势识别器中处理所有四个方向(因为它是连续的,你可以在设置移动动画的UI中为用户提供实时反馈)。

最新更新