我想在我的按钮上添加一个手势识别器,以便在用户滑过按钮框架时可以运行代码。如果向上,向右,向左或向下滑动按钮,我也希望此代码有所不同。
-(void)viewDidLoad
{
[super viewDidLoad];
UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame=CGRectMake(0, 0, 100, 100);
[self.view addSubview:button];
UIGestureRecognizer *swipe=[[UIGestureRecognizer alloc]initWithTarget:button action:@selector(detectSwipe)];
[button addGestureRecognizer:swipe];
}
那么,我是否正确执行了
initWithTarget:action:
?现在,我要如何实现detectSwipe
方法?这是我关于如何实现
detectSwipe
的想法 -(IBAction)detectSwipe:(UIButton *)sender
{
/* I dont know how to put this in code but i would need something like,
if (the swipe direction is forward and the swipe is > sender.frame ){
[self ForwardSwipeMethod];
} else if //same thing for right
else if //same thing for left
else if //same thing for down
}
最佳答案
您可能想使用UISwipeGestureRecognizer。通常不应该使用UIGestureRecognizer,除非您将其子类化。您的代码应类似于以下内容。
UISwipeGestureRecognizer *swipe=[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(detectSwipe)];
swipe.direction = UISwipeGestureRecognizerDirectionRight;
[button addGestureRecognizer:swipe];
关于iphone - 如何初始化UIGestureRecognizer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11925729/