我需要识别执行滑动的方向并知道我视图中的哪个对象发送了它。我现在找到了解决方法,但它看起来很复杂而且很可怕,所以我怀疑有没有最简单的解决方案?我的解决方法是几句话:
- 我将识别器附加到视图上的每个 UIButton 对象。
- 有指示器显示在执行滑动期间点击了哪个按钮
- 我必须检查这个指示器并滑动方向以做出正确的决定,应该移动哪个对象以及它应该向哪个方向移动。
谢谢你的建议。
@synthesize 滑动方向;//显示滑动方向的标签
@synthesize 按钮编号;//标签显示被点击的按钮数量
- (void)viewDidLoad
{
UIButton* 按钮 = [UIButton buttonWithType:UIButtonTypeRoundedRect]; //创建按钮
[按钮 setTitle:@"test1" forState:UIControlStateNormal];
button.frame = CGRectMake(100, 100, 100, 100);
[button addTarget:self //添加选择器,它将更新指示器被点击的按钮,没有点击按钮无法进行滑动
动作:@选择器(更新按钮编号:)
forControlEvents:UIControlEventTouchDown];
[按钮设置标签:1];
[self.view addSubview:button]; //添加按钮查看
[self beginListenToSwipes:button]; //向方法发送按钮,该方法将为 4 个方向添加 UISwipeGestureRecognizer
/*第二个按钮的相同任务*/
UIButton* button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button1 setTitle:@"test2" forState:UIControlStateNormal];
button1.frame = CGRectMake(200, 200, 100, 100);
[button1 addTarget:自我
动作:@选择器(更新按钮编号:)
forControlEvents:UIControlEventTouchDown];
[button1 setTag:2];
[self.view addSubview:button1];
[self beginListenToSwipes:button1];
}
/*每次我们点击按钮(开始滑动时调用此方法并且buttonNumber总是指向当前按钮*/
-(void)updateButtonNumber:(UIButton*)sender
{
self.buttonNumber.text = [NSString stringWithFormat:@"%d",sender.tag];
}
/*方法接收 UIButton 并添加识别器*/
- (void) beginListenToSwipes:(UIButton*)sender
{
UISwipeGestureRecognizer *recognizer;
识别器 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
[识别器设置方向:(UISwipeGestureRecognizerDirectionRight)];
[发送者 addGestureRecognizer:recognizer];
识别器 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
[识别器设置方向:(UISwipeGestureRecognizerDirectionLeft)];
[发送者 addGestureRecognizer:recognizer];
识别器 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
[识别器设置方向:(UISwipeGestureRecognizerDirectionUp)];
[发送者 addGestureRecognizer:recognizer];
识别器 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
[识别器设置方向:(UISwipeGestureRecognizerDirectionDown)];
[发送者 addGestureRecognizer:recognizer];
}
/*滑动执行时调用的方法并显示执行的方向*/
-(void)handleSwipe:(UISwipeGestureRecognizer *)recognizer
{
int i = 识别器.方向;
self.swipeDirection.text = [NSString stringWithFormat:@"%d",i];
}