我的UIView
转换方法在屏幕上监听手势时出现问题。
发生的事情是,如果我进行向左滑动或向右滑动,它会向我的@selector方法发送左右滑动信号。这意味着我无法区分滑动。
这是我的问题代码..我尝试了一些不同的东西,但似乎无法让这一点正确。
- (void) setupSwipeGestureRecognizer {
UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipedScreen:)];
swipeGesture.direction = (UISwipeGestureRecognizerDirectionLeft | UISwipeGestureRecognizerDirectionRight);
[self.view addGestureRecognizer:swipeGesture];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.title = @"Prototype";
//Initalizse the swipe gestuer listener
[self setupSwipeGestureRecognizer];
//alloc and init
self.detailViewA = [[DetailViewController alloc]initWithNibName:@"DetailViewController" bundle:[NSBundle mainBundle]];
self.detailViewB = [[DetailViewControllerB alloc]initWithNibName:@"DetailViewControllerB" bundle:[NSBundle mainBundle]];
// set detail View as first view
[self.view addSubview:self.detailViewA.view];
// set up other views
[self.detailViewB.view setAlpha:1.0f];
// Add the view controllers view as a subview
[self.view addSubview:self.detailViewB.view];
// set these views off screen (right)
[self.detailViewB.view setFrame:CGRectMake(320, 0, self.view.frame.size.width, self.view.frame.size.height)];
}
- (void)swipedScreen:(UISwipeGestureRecognizer*)gesture
{
if (gesture.direction = UISwipeGestureRecognizerDirectionLeft) {
NSLog(@"Left");
}
if (gesture.direction = UISwipeGestureRecognizerDirectionRight){
NSLog(@"Right");
}
}
答案 0 :(得分:3)
swipedScreen:
方法的参数类型为UISwipeGestureRecognizer
,即导致回调被调用的识别器。它不是指用户做出的任何实际手势。在您的情况下,您将此识别器的direction
属性设置为(UISwipeGestureRecognizerDirectionLeft | UISwipeGestureRecognizerDirectionRight)
- 这不会更改。
您必须创建两个识别器,每个方向一个。
答案 1 :(得分:2)
试试这段代码:
(void)swipedScreen:(UISwipeGestureRecognizer*)gesture {
if (gesture.direction == UISwipeGestureRecognizerDirectionLeft) {
NSLog(@"Left");
}
if(gesture.direction == UISwipeGestureRecognizerDirectionRight) {
NSLog(@"Right");
}
}
答案 2 :(得分:1)
Swift 3版本代码:
func setupSwipeGestureRecognizer() {
//For left swipe
let swipeGestureLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.swipedScreen))
swipeGestureLeft.direction = .left
self.view.addGestureRecognizer(swipeGestureLeft)
//For right swipe
let swipeGestureRight = UISwipeGestureRecognizer(target: self, action: #selector(self.swipedScreen))
swipeGestureRight.direction = .right
self.view.addGestureRecognizer(swipeGestureRight)
}
override func viewDidLoad() {
super.viewDidLoad()
setupSwipeGestureRecognizer()
}
func swipedScreen(gesture: UISwipeGestureRecognizer) {
if gesture.direction == .left {
print("Left")
} else if gesture.direction == .right {
print("Right")
}
}
答案 3 :(得分:0)
您尚未正确比较if条件。它应该具有==作为比较运算符。您正在使用=,这使您的条件始终为真。